Rules
Read selectors, properties and values, then write valid declarations.
CodeBhavyaStyle meaningful HTML with clear rules, readable text and an understanding of why declarations win.
Level 10 gave the document a useful structure and keyboard path. CSS now controls how that structure looks. You will write rules, match elements with selectors, choose readable colors and text, and explain why one declaration wins when rules compete.
By the end, create a small external stylesheet for a workshop page and use browser tools to diagnose a style that appears to be ignored. Keep the HTML meaning and keyboard behavior intact while changing presentation.
Read selectors, properties and values, then write valid declarations.
Style text, colors and backgrounds without changing document meaning.
Reason about importance, specificity, source order and inheritance.
Compare controlled examples in the lab and explain the expected result.
CSS means Cascading Style Sheets. A stylesheet contains rules that describe how selected elements should be presented. The same semantic HTML can use different fonts, colors and spacing without changing which element is a heading or button.
A workshop heading stays an h1 when its color changes. A link remains a link when it has a rounded background. Styling a div to look like a button still does not provide native button behavior. Keep the structural choices from Level 10 and treat CSS as the presentation layer.
Browsers also supply default styles. Headings, paragraphs and links have an appearance even before you add a stylesheet. Your rules participate in a system that includes browser defaults, author styles and, sometimes, user styles. This is why styling is more than applying the last file you opened.
h1 identifies the page topic; p holds an explanation.
Choose readable text, a background and visible focus.
Render the structured document using the applicable styles.
A selector identifies which elements a rule can match. Inside braces, each declaration has a property, a colon and a value. A semicolon separates declarations. The property asks what should change; the value describes the requested setting.
h1 {
color: #173451;
font-size: 2rem;
line-height: 1.2;
}Read this rule: for each matching h1, request the stated color, font size and line height. These declarations compete with other applicable declarations for the same properties. They do not erase every other style on the element.
Use a final semicolon even though the last declaration can often omit it. That habit avoids mistakes when you append another property. Comments use /* ... */. CSS does not use JavaScript’s line-comment syntax as an ordinary stylesheet comment.
/* A readable paragraph */
p {
font-size: 1.125rem;
line-height: 1.7;
}A style attribute supplies declarations directly on an element. Useful for a small illustration, but repeated inline styling is difficult to maintain.
A style element in the document head contains rules for that document. It suits a self-contained exercise or demonstration.
A linked CSS file supplies reusable rules. It supports consistent styling across related pages.
<link rel="stylesheet" href="workshop.css">
<style>
.notice { color: #075a83; }
</style>
<p style="color: #173451;">Workshop information</p>The external path is resolved relative to the HTML document unless a base URL changes that behavior. Check the actual filename and folder when the file does not load. A link points to a file; it does not create that file for you.
Do not memorize “external beats internal” or the reverse. Rules in linked sheets and style elements participate in the cascade. For comparable normal author declarations, a style attribute has precedence over stylesheet declarations; importance and other cascade stages still matter.
A type selector matches an element type: p matches paragraphs. A class selector begins with a dot: .notice matches an element whose class list contains notice. An ID selector begins with a hash: #registration matches the element with that ID.
A selector list uses commas to apply a rule to several matching groups. The universal selector * matches elements broadly. Broad rules can be useful for a common foundation, but keep component rules focused so they do not change unrelated parts of a page.
p { line-height: 1.7; }
.notice { background: #eef7fc; }
#registration { border: 1px solid #bdd5e6; }
h1, h2 { color: #173451; }Predict the matches: a paragraph with class notice can match both p and .notice. Their declarations can combine when they affect different properties. A competing declaration for the same property must be resolved by the cascade.
An element can have several classes separated by spaces. Each class can describe a reusable role, such as notice, warning or compact. An ID identifies one element in the document and should be unique. Prefer reusable classes for ordinary component styling; reserve IDs for genuine document identity and related uses.
In HTML you write class="notice featured". In CSS you write .notice or .featured, without adding the dot to the HTML class value. Do not use class=".notice" and expect .notice to match it as the class notice.
<p id="workshop-note" class="notice featured">Bring your HTML notes.</p>
.notice { padding: 1rem; }
.featured { font-weight: 700; }The paragraph receives both reusable styles. The id can also be a fragment-link destination. An ID selector has higher specificity than a class selector, but adding IDs everywhere to win conflicts makes future changes harder.
A space in a selector expresses a descendant relationship. .card p can match paragraphs anywhere inside .card. A greater-than sign expresses an immediate child: .card > p excludes paragraphs nested inside another child element.
An attribute selector can match an attribute’s presence or value. For example, input[type="email"] matches email inputs. The attribute selector is useful when that attribute is a meaningful part of the component’s behavior.
.card p { color: #254864; }
.card > p { margin-top: 0; }
input[type="email"] { border-color: #126d96; }A comma is not a descendant relationship: .card, p selects cards and paragraphs separately. A missing space can change meaning too: .card.featured requires the same element to have both classes, whereas .card .featured requires a featured descendant of a card.
A pseudo-class can match an element in a particular state. :hover commonly matches a pointer hovering over an element. :focus-visible matches when the browser considers a visible focus indicator appropriate, including ordinary keyboard use.
Provide a clear keyboard focus style as well as pointer feedback. A touch device may not have a persistent hover interaction. Do not place essential instructions behind hover alone or remove focus outlines without supplying a visible alternative.
a:hover { text-decoration-thickness: 3px; }
button:focus-visible, a:focus-visible {
outline: 3px solid #126d96;
outline-offset: 3px;
}Pseudo-elements describe a part of an element or generated content. For example, ::first-letter targets an initial letter. Keep essential text in the HTML rather than relying only on generated content, especially when it conveys an action or instruction.
The color property sets text color. Background-color sets a background color. Colors can use named values, hexadecimal notation, rgb() or hsl(). These are different ways to specify a color, not different kinds of semantic content.
.notice {
color: #173451;
background-color: #eef7fc;
}
.warning {
color: rgb(102, 58, 5);
background-color: hsl(45, 100%, 94%);
}Always evaluate the foreground against the background it will actually appear on. A light cyan label on a pale panel may look attractive yet be hard to read. A transparent background can reveal a parent’s background, so inspecting only the local rule may be insufficient.
Do not convey correctness or an error solely through color. Add words, symbols with a meaningful label or another perceivable difference. Use a contrast checker when reviewing the final design; these examples are not a complete accessibility audit.
A background can be a solid color, an image or a gradient. Supply an appropriate color behind an image and ensure text remains readable if the image changes or fails to load. Background images are presentation; essential information belongs in the document with an appropriate alternative.
Gradients can create a visually distinct heading panel without requiring another image file. Keep the transition gentle enough that the text is readable across the entire panel, rather than only at one edge.
.hero {
color: #ffffff;
background: linear-gradient(120deg, #10263f, #19445f);
}Opacity applies to the whole element, including its descendants. Setting opacity: 0.5 on a card makes its text translucent as well as its background. If only the background should be translucent, choose a color with an alpha channel rather than fading the entire component.
Use a font stack so another suitable font is available if the first choice is missing. Set a readable size and line height, then check long paragraphs and small screens. A unitless line-height is useful because descendants can use the multiplier with their own font size.
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 1.125rem;
line-height: 1.7;
}
h1 { font-weight: 700; line-height: 1.2; }
code { font-family: Consolas, monospace; }Font weight changes emphasis, but visual boldness does not turn ordinary text into a heading. Text-align controls text alignment; it is not a general tool for laying out every kind of component. Preserve useful wrapping and avoid fixing paragraph height so tightly that increased text size clips content.
A shorthand such as font can reset associated properties you did not explicitly preserve. For beginner exercises, separate declarations are easier to inspect. When you use a shorthand, learn which properties it resets.
A CSS pixel is a reference unit used for lengths. It does not always correspond to one physical device pixel.
Relative to the root element’s font size. A useful basis for consistent text and spacing.
Relative units whose basis depends on the property. For font-size, em is relative to the parent font size.
A relative value with a property-specific basis. Do not assume every percentage is relative to the viewport.
If the root font size is 16 CSS pixels, 1.125rem corresponds to 18 CSS pixels. That arithmetic is an example with a stated assumption; a user or stylesheet can change the root size. A child at font-size: 1.25em under a 20px parent requests 25px.
Avoid arbitrary text sizes that make reading difficult. Let users zoom, test the page when text grows, and use flexible containers. Level 12 will develop sizing and layout more fully.
For each property on an element, the browser considers applicable declarations and resolves conflicts. Matching is only the first question. Origin and importance, cascade layers where used, specificity and later tie-breakers can affect the winner. Source order is not the first universal rule.
For the beginner examples in this lesson, assume normal author rules in the same layer, with no animations, transitions or scoped-rule complications. Under those assumptions, specificity breaks a conflict, and later source order breaks a remaining tie. The visualizer states these boundaries instead of claiming to simulate every part of CSS.
An external file and an internal style block are both places to put author rules. Their location does not create a fixed priority category that always beats the other. First verify that the file loaded and the selector matches, then inspect the applicable declarations.
.note { color: #075a83; }
.note { color: #663399; }Expected result under the stated assumptions: the later .note rule supplies purple text because both selectors have equal specificity and both declarations are normal author declarations in the same layer.
Compare specificity as components, not a single decimal score. ID selectors form one component; class, attribute and pseudo-class selectors form another; type selectors and pseudo-elements form another. A basic #note selector is more specific than .note, which is more specific than p.
This comparison applies after the relevant earlier cascade decisions. An important declaration can beat a normal declaration in the same author context even when the normal selector is more specific. !important is a declaration flag, not an extra selector or a normal increase to the specificity count.
Use focused rules and inspect conflicts before reaching for !important. Overusing it can make component changes difficult. Inline normal styles can also be overridden by an applicable important author declaration. Important user styles may be used to preserve user needs.
#lesson-note { color: #663399; }
.note { color: #075a83; }
/* Separate example: importance changes the comparison. */
.note { color: #755000 !important; }
#lesson-note { color: #663399; }In the first pair, the matching ID rule wins over the later class rule. In the separate second pair, the important class declaration wins over the normal ID declaration. The lab lets you compare these cases without combining their assumptions.
Some properties, including color and common font properties, are inherited when the child does not have its own winning value for that property. Many box-related properties, such as margin and border, are not inherited by default.
Inheritance is not another highly specific rule on the child. An explicit declaration on a child can replace an inherited value even when the parent selector looks more specific. Ask whether the child has a declaration of its own before comparing the parent’s selector as if it matched the child.
.workshop { color: #176343; }
.workshop p { margin: 0; }
/* The paragraph can inherit the workshop color. */inherit explicitly requests the parent’s computed value for a property. initial requests the property’s initial value; it does not mean “whatever the parent used.” unset follows inheritance for inherited properties and uses the initial value for others. Advanced reverting and layer controls can be studied after the basics.
Trace matching, cascade context, specificity, source order and the result. This is a guided explanation of the fixed examples shown here. Use the timeline or playback controls; no claim is made that the visualizer evaluates arbitrary CSS.
The paragraph has id="lesson-note" and class="note", so both the ID and class rules match.
<p id="lesson-note" class="note">Workshop notice</p>Before comparing priorities, check the selector and confirm that the stylesheet loaded. A non-matching rule cannot style this paragraph.
The preview is a separate local document with controlled rules. Select a case, change the text size and inspect the actual rendered paragraph. Each case explains its expected winner under the stated simple author-style assumptions. The lesson styles outside the preview cannot overwrite its rules.
Compare source-order, ID specificity, inherited color and an important declaration. Read the rules in the same order they are supplied to the preview. The label reports an expected result for the known example; it is not a live browser-computed-style inspector.
Select a case and inspect its rules.
Confirm that the linked stylesheet exists, loads successfully and has the expected content.
Check spelling, classes, IDs, combinators and the actual element structure.
Inspect crossed-out declarations, importance, specificity and order in browser tools.
Check syntax, supported values, inheritance and the background or parent that affects the result.
An invalid or unsupported declaration is generally ignored rather than converted into the value you intended. A missing colon or a malformed block can affect parsing beyond one obvious line. Keep braces balanced and inspect the browser’s parsed rules.
If a change seems absent after deployment, first verify that the deployed file contains it. A local edit that has not been deployed cannot change the public page. A cached resource can also show earlier content; inspect the actual loaded resource before changing unrelated selectors.
Try a small, reversible rule in browser tools to confirm the hypothesis. Then make the permanent change in the correct source file. Do not keep appending broad overrides that affect the header, footer and other lessons by accident.
No. It must match, be valid and survive earlier cascade comparisons. Later order resolves an otherwise equal conflict, not every conflict.
No. Both can contain author rules. Their cascade context, specificity and order decide applicable conflicts.
Classes identify reusable groups and can be combined. An ID identifies one element and should be unique; an ID selector has a higher specificity component.
Inheritance supplies certain parent values when the child has no overriding value. It does not mean the parent selector also matches the child.
No. It flags a declaration as important. Importance is considered at a different cascade stage from selector specificity.
The number acts as a multiplier with the element’s font size, which can make inherited text spacing easier to manage.
No. Appearance does not provide the semantics and keyboard behavior of a native control.
Readability depends on the actual combination, including transparency, parent backgrounds and images behind the text.
Repair color = blue to a valid declaration. Expected: color: blue; is parsed as the requested color.
Use class="notice featured" with .notice and .featured rules. Expected: the same element can receive declarations from both.
Put one paragraph directly inside a card and another inside a nested section. Expected: .card p matches both; .card > p matches only the direct child.
Write two .note color rules, then reverse their order. Expected: the later rule wins in the stated equal normal author context.
Put the class rule after a matching ID rule. Expected: the normal ID declaration still wins in the same context.
Give a parent a color and border. Expected: the paragraph can inherit the color, while the border does not automatically become the paragraph’s border.
Assume a 20px parent and set the child font-size to 1.25em. Expected requested font size: 25px under that assumption.
Keep a visible focus style and increase preview text size. Expected: the active control stays identifiable and text is not clipped.
A collection of CSS rules defining presentation.
A pattern used to match elements for a rule.
A property/value pair with an optional importance flag.
The aspect of presentation being specified, such as color.
The process that resolves competing applicable declarations.
Selector components used in the cascade after relevant earlier decisions.
The order used to resolve a remaining equal-priority conflict.
The transfer of certain parent values when a child lacks an overriding value.
A selector feature describing a state or other condition.
A property value after the relevant computation stage, before some later layout-dependent resolution.
Take the standalone workshop page from Level 10 and create workshop.css next to it. Link the stylesheet in the head. Use classes for the hero, notice and practice panels; style the headings, body text and native disclosure while keeping all existing semantic tags and keyboard controls.
Use a readable font stack, a flexible text size and a unitless line-height. Choose contrasting text and background colors. Provide a clear focus-visible style and avoid a fixed panel height that clips enlarged text. Keep decorative backgrounds separate from essential content.
Add two deliberately competing normal class color rules to a practice notice and predict their winner. Then compare a matching ID rule in a separate example. Record the assumptions that make your predictions valid and inspect the winning declaration in browser tools.
Success criterion: the external file loads, the selectors match only the intended content, the page remains operable by keyboard, and you can explain the conflicting color result. Level 12 will build on this foundation with the box model and layout.
Before marking complete, write and link a valid stylesheet, demonstrate class matching, explain an equal-rule conflict and an inherited value, and preserve a visible keyboard focus indicator. Completion is a local study milestone, not a score or design certification.