What is a CSS rule?
A CSS rule is a set of instructions that defines how specific HTML elements should be styled on a webpage. Each CSS rule consists of a selector, which targets the HTML element(s), and a declaration block, which contains one or more style declarations.
CSS Rule Structure
selector { property: value; property: value;}
Selector: Identifies the HTML element(s) you want to style (e.g., p, .class, #id).
Property: The style attribute you want to change (e.g., color, font-size).
Value: The specific setting for the property (e.g., blue, 16px).
Exmaple
In this example, the selector p targets all <p>
(paragraph) elements, setting their text color to green and font size to 16px.
Learn ways to include CSS in HTML in our How to Include CSS in HTML chapter.
The Concept of Cascading in CSS
1. Inheritance:
Some CSS properties, like font
and color
, are inherited from parent elements to child elements. This means if a parent element has a certain style, its children will automatically adopt that style unless overridden.
2. Specificity:
CSS rules can be defined with different specificity (e.g., inline styles, IDs, classes). When multiple rules apply, the one with the highest specificity will take precedence. If specificity is equal, source order will determine which rule is applied.
Internal CSS takes priority over an ID selector (#id) overrides a Class selector (.class) or an element (type) selector (p, h1, etc). Class selector (.class overrides a type selector (p, h1, etc)
Inheritance:
Some CSS properties (like font and color) are inherited from parent to child elements.
Source Order:
When styles conflict, the last rule written takes precedence.
When Declaration Conflicts:
When declarations conflict within the same selector, the last declaration written takes precedence.
Importance:
A rule with !important overrides other rules, regardless of specificity or order (use sparingly, as it can make code harder to maintain).