Lesson · HTML & CSS Basics
CSS selectors and the cascade
CSS rules match elements and describe how they should be presented.
What you will learn
- Write a CSS rule
- Use class selectors for reusable styles
- Understand specificity and source order
A rule has two parts
A CSS rule contains a selector and a declaration block. The selector identifies which elements are affected; each declaration pairs a property with a value. Braces contain declarations and semicolons separate them. Consistent formatting makes missing punctuation and accidental selector matches easier to notice.
Prefer reusable classes
A type selector such as p affects matching elements. A class selector begins with a period and can be reused across several elements. An ID selector begins with a hash and identifies one element in a document; it is often better suited to a unique anchor than a general visual style.
Resolve competing rules
When more than one rule applies, the cascade considers origin, importance, specificity, and source order. A highly specific selector can be difficult to override later. Start with simple selectors and avoid using !important as a routine fix; it can turn a small conflict into a harder debugging problem.
Connect a stylesheet
A link element in the document head can load a local stylesheet. A correct selector still has no effect if the path is wrong or the stylesheet failed to load. Inspect the browser's developer tools when a rule appears ignored, and check both the request and the computed style.
Debug the cascade from the element
When a declaration loses, inspect the element's computed styles and find the rule that supplied the winning value. Then simplify the competing selectors or remove an obsolete declaration rather than increasing specificity repeatedly. A small design token such as a custom property can centralize a reused color, but it should represent a real design choice.
.lesson-note {
color: #17324d;
background-color: #eaf3fb;
padding: 1rem;
}
Practice exercise
Style every element with class lesson-note using readable text color and internal spacing.
Show a hint
Start with a class selector and choose color and padding properties.
Show one possible solution
Write a .lesson-note rule with a color value and a padding value. The HTML element must include class='lesson-note'.
Quick check
A period begins a class selector; a hash begins an ID selector.