CSS Basics
BeginnerLesson 4 of 8 in Web Development Basics Course
What you will learn
- Write valid CSS rules, connect a stylesheet to an HTML page, and start from the styles the browser already applies, using developer tools to see what is going on.
- Write CSS rules and connect a stylesheet to a pageRead and write the parts of a CSS rule, choose between an external stylesheet, a
<style>element and inline styles, and know what the browser does with mistakes. - Start from the browser's default styles and inspect themRecognize the styles every browser applies before yours, decide what to reset, and use developer tools to find out why an element looks the way it does.
- Write CSS rules and connect a stylesheet to a page
- Target exactly the elements you mean with type, class and ID selectors, attribute selectors, pseudo-classes, pseudo-elements and combinators.
- Select elements by type, class and IDSelect elements by name, class or ID, combine selectors that must match the same element, and group several selectors in one rule.
- Select by attributes, states and parts of elementsUse attribute selectors, pseudo-classes for states and positions, and pseudo-elements that style part of an element or add generated content.
- Combine selectors by their place in the pageSelect elements by their relationship to other elements in the HTML tree: anywhere inside, directly inside, right after or somewhere after another element.
- Select elements by type, class and ID
- Work out which declaration applies when several rules set the same property, calculate specificity, and explain how elements get values that no rule gave them directly.
- Follow the cascade to find the winning declarationApply the cascade's steps (origin and importance, specificity, then order of appearance), and use inline styles,
!importantand cascade layers with care. - Calculate and compare specificityScore any selector in the ID–class–type format, compare scores column by column, and keep specificity low so styles stay easy to override.
- Use inheritance and the global keywordsKnow which properties pass from parent to child, use inheritance to write less CSS, and control it with
inherit,initial,unsetandrevert.
- Follow the cascade to find the winning declaration
- Write colors in the main CSS notations, make text readable against its background, and choose between absolute and relative units for text, spacing and sizes.
- Write colors with keywords, hex, rgb() and hsl()Use color keywords, hex codes,
rgb()andhsl(), add transparency, and check that text contrasts enough with its background. - Choose lengths and unitsUse pixels,
em,rem, percentages and viewport units correctly, know what each relative unit is measured against, and combine units withcalc().
- Write colors with keywords, hex, rgb() and hsl()
- Explain how every element is drawn as a box of content, padding, border and margin, calculate its size, and control the space inside and between boxes.
- Calculate box sizes from content, padding, border and marginName the four parts of a box, write the spacing shorthands, and calculate an element's size in the standard and alternative box models.
- Control spacing between block and inline boxesPredict how block, inline and inline-block boxes take up space, center a block with automatic margins, and recognize when vertical margins collapse.
- Calculate box sizes from content, padding, border and margin
- Choose and load fonts, make text readable, style lists and links, and decorate boxes with backgrounds, gradients, borders, rounded corners and shadows.
- Choose fonts and load web fontsWrite font stacks with fallbacks, set size, weight and style, use the
fontshorthand, and load a custom font with@font-face. - Style text, lists and links for readabilitySet line height, alignment, decoration, case and spacing, change list markers and indentation, and give links clear, accessible states.
- Add background colors, images and gradientsFill boxes with colors, images and gradients, control how background images repeat, scale and sit, and write the
backgroundshorthand. - Draw borders, rounded corners, outlines and shadowsWrite border shorthands for all or single sides, round corners with
border-radius, and add outlines and shadows without changing the layout.
- Choose fonts and load web fonts
CSS study guide
1Connect CSS and inspect the result
CSS turns a meaningful HTML page into a page with chosen colors, type and spacing. A working rule needs both valid syntax and a connection to the document. The browser also brings its own styles, so you always begin with an existing appearance. Learn to connect an external stylesheet, make a small change, and follow that change in developer tools when the result differs from what you expected.
1.1 Rules, declarations and stylesheets
HTML describes content and meaning. CSS, short for Cascading Style Sheets, describes presentation: colors, fonts, spacing, borders and backgrounds. Changing a stylesheet can give the same HTML a different appearance without changing its headings, paragraphs or links.
Read a rule
p {
color: navy;
font-size: 18px;
}
The selector p matches paragraphs. The curly braces enclose the declaration block. Each declaration has a property, a colon, a value and a semicolon. Here, color and font-size are properties; navy and 18px are values. Line breaks and spaces between these parts make the code easier to read without changing its effect.
A semicolon separates one declaration from the next. The last one is optional, but keeping it prevents mistakes when you add another line. In color: navy font-size: 18px;, the browser reads one invalid color value. It cannot recover the two declarations you intended, so neither style is set by that text.
Connect the CSS
An external stylesheet is a separate CSS file linked from the HTML head:
<link rel="stylesheet" href="css/styles.css">
This path means that a folder named css sits next to the HTML file and contains styles.css. One external file can style several pages. Saving a change there updates the rules those pages load.
A style element in the head holds rules for one page. An inline style attribute holds declarations for one element, such as <p style="color: crimson;">Hello.</p>. External stylesheets are usually easier to maintain. Normal inline declarations also outrank normal author stylesheet rules, which can make later changes awkward.
For a first result, put body { font-family: Arial, sans-serif; } and h1 { color: darkslateblue; } in the linked file. Reload the page. Body text takes Arial where available, with a sans-serif fallback; the heading changes color. Controls such as buttons can retain their own browser font until you explicitly make it inherit.
Find syntax and path mistakes
Browsers skip invalid declarations and continue. color: 12px; is invalid because a length is not a color. font-size: 16 px; is invalid because the number and unit must touch. A misspelled property is ignored too. A valid border declaration in the same block can still work, so one visible change does not prove every declaration is valid.
CSS comments use /* Header styles */ and can span lines. // does not start a CSS comment; it can cause following code to be skipped. Property names and ordinary keyword values are case-insensitive; keep them lowercase by convention. Class names and file paths must match their actual spelling and capitalization.
If no styles appear, check the request in the Network panel. A wrong path such as style.css can return 404 even though the HTML page itself opens normally.
Treat shorthands as complete settings
A shorthand sets several related properties at once. margin: 10px 20px; sets all four margins. Omitted parts return to their initial values: background-image: url("sky.jpg"); followed by background: lightblue; removes the image. Put a shorthand first, then any longhand exceptions that should survive.
Key Takeaways
- Write each declaration as
property: value;inside a rule. - Link an external stylesheet from the HTML
head; resolve its path from the HTML file. - A browser skips invalid CSS and continues with valid declarations.
- Use
/* ... */for CSS comments. - A shorthand resets related longhands that it leaves out.
1.2 Browser defaults and developer tools
A plain HTML page still has large headings, paragraph spacing, list markers and underlined links. These come from the user-agent stylesheet, the browser's built-in CSS. Your styles begin from these defaults; an unstyled page is not a page without CSS rules.
Choose meaning before appearance
Typical defaults include an 8px body margin, 1em vertical paragraph margins, and 40px start padding on lists. Heading defaults include 2em for h1 and 1.5em for h2, with h1 vertical margins of 0.67em. Strong text is bold; emphasized text is italic. Unvisited links are usually blue and visited links purple. Browser settings and implementations can affect defaults, so inspect the actual page when precision matters.
The default text size is commonly 16px, with a font chosen in browser settings. Readers can change that size. Relative font sizes can follow their choice.
Choose an HTML element for its meaning, then style it. If an h2 looks too large, use h2 { font-size: 1.25rem; }. Choosing an h4 solely for smaller type would change the heading structure. Changing the CSS size leaves the second-level heading's meaning intact.
Defaults also determine how elements occupy space. Paragraphs and sections normally form block boxes. Spans and links normally flow inside lines. List items have display: list-item, giving them a block-level box and a marker. A CSS display change alters the box behavior while preserving the element's HTML meaning.
Reset only what you intend
A reset removes selected defaults. body { margin: 0; } removes the outer gap. A broad rule such as * { margin: 0; padding: 0; } also removes paragraph spacing and list indentation, which you then need to rebuild. A normalize approach keeps useful defaults and adjusts inconsistencies.
Form controls often have directly assigned browser fonts. To make them match the page, write:
button, input, select, textarea {
font: inherit;
}
Start the HTML document with <!DOCTYPE html>. It selects standards mode. Omitting the doctype can trigger quirks mode, where older compatibility behavior changes some sizing and other CSS results.
Inspect the property that surprises you
Right-click an element and choose Inspect. The Styles panel shows matching rules, including browser rules labeled as user-agent styles. A crossed-out declaration lost to another declaration; a warning can mark invalid CSS. Winners are chosen property by property, so a rule can lose its color while still supplying its padding.
The Computed panel shows final property values and the box model's content, padding, border and margin. If a heading has an unexpected gap, inspect its margin before adding padding to a different element. Test a change directly in developer tools, then copy the working rule to your stylesheet: inspection edits disappear on reload.
When a style fails, follow a useful order: check that the stylesheet loaded, that the selector matches, that the declaration is valid, that it wins, and that the property affects this kind of box. A valid width: 200px still does not size an ordinary inline span.
Key Takeaways
- The user-agent stylesheet supplies readable defaults before your CSS applies.
- Choose HTML elements by meaning and change their appearance with CSS.
- A reset removes defaults that you may need to add back.
- Use standards mode with
<!DOCTYPE html>. - Inspect matching rules, validity and crossed-out declarations before changing code.
- Save successful developer-tools experiments in the stylesheet.
2Select exactly the right elements
A selector describes which elements a rule reaches. Some selectors match names or attributes; others match a state, a part of an element, or a relationship in the HTML tree. Small punctuation changes matter: a space, a comma and a dot each make a different request. Work from the element you want to style back through the conditions that identify it, so a rule reaches all the intended elements and leaves the others alone.
2.1 Type, class, ID and compound selectors
A selector answers a practical question: which elements should receive these declarations? Start with the simplest match that expresses the role you want. A class can be reused across many elements without tying the style to one location on the page.
Match names and attributes
| Selector | Matches |
|---|---|
p | Every paragraph |
.warning | Every element with the class warning |
#site-header | The element with the ID site-header |
* | Every element |
A type selector is an element name. A class selector begins with a dot; an ID selector begins with #. The punctuation belongs to the CSS selector, not the HTML attribute value. Write <p class="warning">, not <p class=".warning">.
An element can have several classes separated by spaces. Both <p class="warning"> and <div class="box warning"> match .warning. An ID must be unique within a page. Its high specificity also makes ID-based styles harder to override, so classes are usually the main reusable styling tool.
Use names that describe a role, such as .error-message or .product-card. A name like .red-text becomes misleading if the design changes to another color. Class names are case-sensitive: .Warning and .warning differ. A name beginning with a digit needs escaping in a CSS selector; choosing .three-columns avoids the invalid unescaped form .3-columns.
Require several conditions on one element
Writing selectors together makes a compound selector. The same element must satisfy every part. p.intro matches paragraphs that have the class intro. .card.featured matches an element with both classes.
<p class="note important">Doors open at 19:00.</p>
<p class="note">Bring your ticket.</p>
.note { color: #333333; }
.important { font-weight: bold; }
p.note.important { border-left: 4px solid crimson; }
First find the matches. Both paragraphs have note, so both get dark gray text. Only the first has important, so only it becomes bold. The compound selector adds the left border to that same first paragraph because it is a p with both classes. No extra wrapper is needed.
A space changes the task: p .intro selects an element with class intro inside a paragraph. It does not select the paragraph itself. Keep the parts together when they describe the same element.
Share a declaration block
A comma creates a selector list:
h1, h2, h3 { font-family: Georgia, serif; }
Each selector independently matches its heading level. Without the commas, h1 h2 h3 would ask for an h3 inside an h2 inside an h1.
An invalid selector in an ordinary selector list can invalidate the entire rule. h1, h2..title, h3 styles none of those headings because the doubled dot is invalid. When a shared rule appears absent, check every selector in the list, not only the one for the element you inspected.
Key Takeaways
- A class can appear on many elements, and one element can have several classes.
- An ID must be unique on the page and has high selector specificity.
p.introrequires both conditions on one element;p .introdescribes a descendant.- Commas create independent selectors that share declarations.
2.2 Attributes, states and parts
Some styling conditions are already present in HTML attributes. Others depend on what the reader is doing or where an element sits among its siblings. CSS can match these conditions without adding a class for each one.
Select an attribute or its value
Attribute selectors use square brackets. [alt] matches the presence of an attribute, even if its value is empty. input[type="email"] requires the exact attribute value.
| Pattern | Meaning |
|---|---|
[href^="https"] | Value starts with https |
[href$=".pdf"] | Value ends with .pdf |
[href*="example"] | Value contains example |
[class~="note"] | A space-separated list contains the word note |
| `[lang | ="en"]` |
Add i before the closing bracket to ignore case, as in a[href$=".pdf" i]. It also reaches a link ending in .PDF. A whole-word match prevents note from accidentally matching a longer class word such as notebook.
Select a state or position
A pseudo-class uses one colon: :hover, :focus, :checked or :disabled. :focus-visible selects a focused element when the browser determines that a visible indicator is needed, commonly during keyboard navigation.
A link can be visited and hovered at the same time. For competing rules with the same specificity, write link states in this order: :link, :visited, :focus, :hover, :active. A later visited-color rule would otherwise beat an earlier hover-color rule on a visited link. Browsers restrict :visited to certain color changes for privacy; setting its font weight does not work, and transparency cannot reveal visit history.
Structural pseudo-classes count siblings. :first-child means the first element child of its parent. In <article><h2>News</h2><p>Update</p></article>, p:first-child matches nothing. p:first-of-type does match that paragraph.
:nth-child(3) selects the third child. odd selects positions 1, 3, 5; even selects 2, 4, 6. In :nth-child(3n+1), start with n = 0, then 1, 2 and 3: the matched positions are 1, 4, 7 and 10. li:not(:last-child) excludes the last item, making it useful for separators only between items.
Style a part or add a cue
A pseudo-element uses two colons. ::first-line and ::first-letter style text parts; ::marker styles list markers, ::placeholder a field's hint, and ::selection highlighted text. The older single-colon forms for before, after, first-line and first-letter still work.
.required::after {
content: " *";
color: crimson;
}
::after creates content inside the selected element after its existing content. ::before creates it before. Both need a content value; even content: "" creates a decorative box. Essential wording belongs in the HTML, where it remains actual document content. Use these pseudo-elements for decoration or small cues, since generated text is not reliably selectable or copyable like HTML text.
Key Takeaways
- Attribute operators distinguish presence, exact values, text fragments and whole words.
- A pseudo-class selects a state or position; a pseudo-element styles a part or generated content.
:first-childcounts all element siblings, while:first-of-typecounts the same element type.- Link states can overlap, so competing state rules need a deliberate order.
::beforeand::afterneedcontent; essential information belongs in HTML.
2.3 Relationships in the HTML tree
HTML elements form a tree. An element directly inside another is its child; anything nested inside it is a descendant. Elements sharing a parent are siblings. A combinator connects selectors by one of these relationships.
Follow the relationship to the target
| Combinator | Example | Target |
|---|---|---|
| Space | nav a | Any link anywhere inside a nav |
> | .menu > li | An li directly inside .menu |
+ | h2 + p | A paragraph immediately after an h2, with the same parent |
~ | h2 ~ p | Any later paragraph sibling of an h2 |
The rightmost part names the element that receives the declarations. h2 + p styles the paragraph, not the heading. Both sibling combinators look forward through siblings; neither selects a parent or a previous sibling.
Trace a nested list
<ul class="menu">
<li>Guides</li>
<li>Topics
<ul>
<li>Typography</li>
</ul>
</li>
</ul>
.menu li matches all three list items because all three are descendants of the outer list. .menu > li matches only “Guides” and “Topics”: their parent is the list with class menu. The “Typography” item's parent is the inner ul, which does not carry that class.
This distinction matters when top-level items need large padding but nested items need compact spacing. A descendant selector reaches every depth unless another condition narrows it.
Trace following siblings
<article>
<h2>Opening hours</h2>
<p>Visit in the morning.</p>
<aside>Closed on holidays.</aside>
<p>Booking is optional.</p>
</article>
h2 + p matches “Visit in the morning.” It does not skip the aside to find another paragraph. h2 ~ p matches both paragraphs because both follow the heading and share its parent. If a paragraph were inside the aside, it would not be a sibling of the heading and would not match either selector for that reason.
Combine relationships without overreaching
.sidebar > ul a:hover matches hovered links anywhere inside a ul whose direct parent has class sidebar. Read from the right: a hovered link; inside a list; that list directly inside the sidebar. The space allows intermediate elements between the list and the link.
Combinators do not add specificity. The selector's element, class, ID and other matching parts still do. Long chains can therefore make rules harder to maintain even though the relationship symbols add no points: changing the HTML nesting can break their matches. A descriptive class on the target, such as .menu-link, often expresses a reusable role more clearly.
When a rule fails to match, inspect the actual tree instead of counting visual gaps. Two elements can appear next to each other on screen while having different parents in the HTML. Comments and whitespace do not count as element siblings for these combinators.
Key Takeaways
- A space reaches descendants at any depth;
>reaches direct children. +reaches the immediately following element sibling;~reaches later matching siblings.- The rightmost selector names the element being styled.
- Combinators add no specificity, but long selector chains depend heavily on the HTML structure.
3Work out which declaration wins
Several rules can match one element, and each can contribute a different part of its appearance. The cascade chooses a value for each property through a sequence of comparisons. Specificity matters only after higher-priority comparisons tie. Inheritance then helps text styles flow through the page without a rule on every element. Keeping these jobs separate makes a crossed-out declaration much easier to explain and fix.
3.1 The cascade, inline styles and layers
The cascade chooses a winning declaration for each property on each element. It does not choose one whole rule and discard all the others. With p { color: gray; font-size: 18px; } and .lead { color: black; }, a paragraph with class lead can take its color from the class rule and its size from the type rule.
Compare in the correct order
First remove declarations that do not apply: their selectors must match, and any conditions must hold. Then compare origin and importance, including cascade layer priority. Normal inline author styles outrank normal author stylesheet rules. When declarations remain tied at these earlier stages, compare specificity; use order of appearance for a remaining tie.
| Normal declaration origin | Priority |
|---|---|
| Author: the site's CSS | Highest of these three |
| User: a reader's custom styles | Between author and browser |
| User agent: browser defaults | Lowest |
Two equal-priority .button rules setting different background colors are resolved by order: the later one wins. Stylesheets linked later in HTML come later for these ties too. A file arriving faster over the network does not make it later in the cascade.
Understand importance before adding it
An inline declaration such as style="color: purple;" beats normal author stylesheet selectors, even selectors with IDs. An author stylesheet declaration with !important can beat that normal inline declaration.
<p class="note" style="color: purple;">Check the time.</p>
p { color: gray !important; }
.note { color: blue; }
The paragraph is gray. Importance is compared before selector specificity or the normal inline advantage. If the inline color also has !important, that important inline declaration wins against the important author stylesheet rule.
For important declarations, origin priority reverses: important browser declarations outrank important user declarations, which outrank important author declarations. This protects rules that readers or browsers must enforce. Within one origin, inline and layer precedence still come before specificity and source order.
Using !important for every conflict creates increasingly hard overrides. Prefer a simpler selector or a deliberate order. Overriding third-party rules you cannot edit can justify an important declaration; it should be a considered exception.
Group rules into cascade layers
@layer reset, base, components;
@layer base {
p { margin: 0 0 1rem; }
}
This declares the layer order before their rules. For normal declarations, later layers beat earlier layers regardless of selector specificity. Normal rules outside any layer beat normal layered rules. A low-specificity component rule can therefore override a high-specificity base rule without adding IDs.
Important declarations reverse that layer order: earlier layers beat later ones, and important layered declarations beat important unlayered declarations. This reversal preserves important protections in foundational layers. When investigating a conflict, establish the winning origin, importance and layer group before spending time counting selector parts.
Key Takeaways
- The cascade selects declarations separately for each property.
- Origin, importance, inline priority and layer priority come before specificity.
- Normal inline author styles beat normal author stylesheet rules.
!importantchanges priority; it does not add specificity.- Normal layer priority favors later layers and unlayered rules; important layer priority reverses.
- Order of appearance resolves declarations only after earlier comparisons tie.
3.2 Specificity without guesswork
Specificity measures the selector's targeting weight. Compare it only among declarations still tied in the earlier cascade stages, including origin, importance, layer and inline priority.
Count three columns
Write specificity as ID–CLASS–TYPE, such as 0-1-1.
| Column | Count each of these |
|---|---|
| ID | ID selectors such as #menu |
| CLASS | Classes, attribute selectors and ordinary pseudo-classes |
| TYPE | Type selectors and pseudo-elements |
The universal selector * and combinators add nothing. For a[href^="https"]:focus, count no IDs, two CLASS parts (the attribute and :focus) and one TYPE part (a). The result is 0-2-1.
More examples: .nav a is 0-1-1; ul li a:hover is 0-1-3; #main .card > h2 is 1-1-1; article p::first-line is 0-0-3. A pseudo-element counts with types even though its name begins with colons.
Compare from the left
Compare IDs first. If they tie, compare CLASS; if those tie, compare TYPE. Only equal triples move on to source order. These are separate counts, not digits in a decimal number: 0-11-0 still loses to 1-0-0. Extra classes cannot carry over into an ID.
<nav id="site-nav">
<a class="active" href="/">Home</a>
</nav>
#site-nav a { color: white; }
nav a.active { color: orange; }
.active { color: yellow; }
Assume these are normal declarations in the same author layer. Their scores are 1-0-1, 0-1-2 and 0-1-0. The first wins, so the link is white. Its ID column settles the comparison before any class or type counts matter.
#site-nav .active would win with 1-1-0, but a class-based design is easier to extend: .site-nav a can supply the base style, with .site-nav .active changing the active link. This keeps specificity low and fairly even.
Know the functional exceptions
:is(), :not() and :has() add no weight for the function itself. Their most specific argument supplies the weight. Thus li:not(.done) is 0-1-1, and :is(#intro, p) a is 1-0-1. Count the most specific selector in the argument list, not the one you find visually closest to the element.
:where() and everything inside it always contribute zero. :where(#main) p therefore scores 0-0-1. It is useful for defaults that should be easy to override.
The distance to an ancestor does not count. body h1 and html h1 both score 0-0-2, so a later declaration wins their tie. Inline styles are handled before selector specificity, and !important belongs to importance. Neither is another ordinary selector part to add to the triple.
Key Takeaways
- Count IDs, then classes/attributes/pseudo-classes, then types/pseudo-elements.
- Compare triples column by column; a lower column cannot outweigh a higher one.
- Combinators and
*add zero. :is(),:not()and:has()take their most specific argument;:where()contributes zero.- Ancestor distance does not affect specificity.
3.3 Inherited values and deliberate resets
Inheritance lets a child receive a value from its parent when that property normally inherits and no declaration supplies a different value on the child. It is why one body rule can establish the text color and font for much of a page.
Separate inherited text from box settings
Most text properties inherit: color, font properties, line-height, letter-spacing, text-align and text-transform. List styles and visibility also inherit. Box properties such as margin, padding, border, width, height, backgrounds, display and box sizing do not.
body { color: #222222; font-family: Georgia, serif; }
h1, h2 { font-family: Arial, sans-serif; }
footer { color: #666666; }
Ordinary body text uses dark gray Georgia. Headings get their directly assigned font family and keep the inherited color. Footer text inherits Georgia while its color changes locally.
A child's transparent background lets the parent's background show through; that does not mean the child inherited the background color. Likewise, children of a bordered box do not automatically get their own borders.
Direct assignments beat inherited candidates
With #content { color: red; } and p { color: blue; }, a paragraph inside the content area is blue. The ID's specificity does not compete with the paragraph rule because the declarations target different elements. The paragraph already has a directly assigned color, so it does not need the inherited red.
Children generally inherit computed values. If a section has font-size: 20px and its child has font-size: 0.8em, that child computes to 16px. A paragraph inside it inherits 16px; it does not multiply by 0.8 again. A unitless line height is useful because the inherited value remains a multiplier for each child's own font size.
Choose what a reset means
| Keyword | Effect |
|---|---|
inherit | Take the parent's computed value |
initial | Use the CSS property's initial value |
unset | Inherit an inherited property; initialize a non-inherited one |
revert | Roll back the current origin's styles |
revert-layer | Roll back the current cascade layer's styles |
For author CSS, revert exposes user or browser-origin styling. The difference matters on a div: display: initial gives the property's initial inline, while display: revert restores its usual browser block display. An initial value belongs to the CSS property; a browser default can depend on the HTML element.
inherit works even on a property that normally does not inherit, such as border: inherit. button, input { font: inherit; } replaces the controls' directly assigned fonts with their parent's font. all: unset resets almost every property at once, which also removes useful built-in appearance.
One apparent exception is an underline. text-decoration is not inherited, but a parent's underline is drawn through its inline descendants. Setting text-decoration: none on a nested span cannot erase the parent's line. Remove it from the parent and apply it only to the text that should carry it.
Key Takeaways
- Most text properties inherit; box properties generally do not.
- A directly assigned child value takes priority over an inherited parent value.
initialmeans the CSS initial value;revertcan restore browser element defaults.unsetchooses inheritance or initialization according to the property.revert-layerremoves the current layer from that property decision.- A parent underline is drawn through inline descendants without being inherited.
4Write colors and choose useful units
CSS values need a clear meaning as well as valid spelling. A color can be written by name, by channel values or by hue, and transparency changes what the reader finally sees. A length can follow text, a container or the browser window. Learn which reference each unit uses, then work through the value before checking it in the browser. These choices help styles stay readable when content and reader settings change.
4.1 Color values, alpha and contrast
color sets text color. Backgrounds, borders, outlines, decorations and shadows accept color values too. The same color can be written in several forms; choose a notation that makes the intended change easy to understand.
Read names and hexadecimal channels
CSS has about 150 named colors, including navy, tomato and rebeccapurple. Names are convenient for quick experiments, but their everyday meanings can surprise you: green is #008000, while bright pure green is lime, or #00ff00. Exact values remove that uncertainty.
A six-digit hex color has three channel pairs: red, green and blue. Each pair ranges from 00 to ff, equivalent to 0 through 255. All zero gives black; all maximum gives white. Equal pairs produce a gray, as in #808080.
Three-digit hex doubles each digit: #f0a expands to #ff00aa. It does not add zeros. A color such as #1e90ff cannot be shortened because not every pair repeats its digit. Capital and lowercase hex letters mean the same values.
To convert a pair, multiply its first digit by 16 and add the second. The letters a through f mean 10 through 15. For #1e90ff, 1e gives 30, 90 gives 144 and ff gives 255. The matching RGB notation is rgb(30 144 255). Older code may use commas or rgba(); those forms still work.
Describe hue or transparency
hsl() names hue, saturation and lightness. Hue is an angle: 0 or 360 is red, 120 green and 240 blue. Saturation runs from gray at 0% to full color at 100%. Lightness runs from black at 0% to white at 100%. A pure hue has 100% saturation and 50% lightness, as in hsl(0 100% 50%). Changing only lightness makes related dark and pale versions.
An alpha value follows a slash: rgb(0 0 0 / 0.6) is black at 60% opacity. Zero is fully transparent and one fully opaque. Eight-digit hex adds an alpha pair: #00000080 has 128 out of 255, about 50% alpha. transparent is fully transparent.
.notice {
color: white;
background-color: rgb(0 0 0 / 0.6);
}
Only the background is partly transparent here. opacity: 0.6 would instead fade the whole element, including its text and children. That difference matters when you want solid, readable text over a tinted surface.
Reuse color and check the result
currentColor means the element's own text color. With color: #0055aa; border: 2px solid currentColor;, the border follows the text. Changing the text color also changes that border without repeating a color value.
WCAG 2.2 level AA requires at least 4.5:1 contrast for normal text and 3:1 for large text, about 24px or about 18.5px when bold. #767676 on white is about 4.54:1; #999999 on white is about 2.85:1 and fails both thresholds. Use a contrast checker or the browser's color tools on the actual foreground/background pair, including the effect of transparency.
Key Takeaways
- Hex colors encode red, green and blue; three-digit hex repeats each digit.
rgb()gives channels, whilehsl()gives hue, saturation and lightness.- Alpha in a background color affects that color;
opacityfades the whole element. currentColorfollows the element’s text color.- Normal text needs at least 4.5:1 contrast at WCAG AA; large text needs 3:1.
4.2 Pixels and relative lengths
A length combines a number with a unit, such as 16px or 1.5rem. There is no space between them. A nonzero width needs a unit: width: 300; is invalid. Zero can omit its unit. Some properties deliberately take plain numbers, including line-height: 1.5, opacity: 0.8 and font-weight: 700.
Match the unit to its reference
| Unit | Reference |
|---|---|
px | A CSS reference pixel |
em in font-size | The parent's font size |
em in spacing and other lengths | The element's own font size |
rem | The root element's font size |
% | A reference determined by the property |
vw, vh | Viewport width or height |
ch | The width of the font's zero character |
A CSS pixel is not necessarily one physical screen dot. High-density screens can use several device pixels for a CSS pixel. Fixed unit relationships include 1in = 96px = 2.54cm and 1pt = 1/72in. Thus 12pt equals 16px and 1cm is about 37.8px. Those conversions do not guarantee a physical measurement on every screen.
Work through font-relative values
Suppose a parent has a 16px font and its child has font-size: 1.25em; padding: 2em;. Calculate font size first: 1.25 times 16px gives 20px. The padding then uses the child's own size, so 2 times 20px gives 40px on each side.
Nested em font sizes can compound. With li { font-size: 1.25em; }, three nested levels starting from 16px become 20px, 25px and 31.25px. 1.25rem instead gives 20px at every level when the root is 16px.
Leaving the root size at the browser default, or setting it as a percentage, lets relative text respond when a reader changes that default. A fixed html { font-size: 16px; } overrides that setting. A practical pattern is rem for font size and em for a button's padding, so its spacing grows with its own text.
Check percentages and the viewport
The property determines the percentage reference. A containing block supplies a box-size reference; in these normal-flow examples it is usually the parent’s content area. A width: 40% child in a 600px containing block is 240px wide before any content-box padding or border. font-size: 150% uses the parent's font size. Even top and bottom percentage padding and margins use the containing block's width, not its height.
1vw is 1% of viewport width; 1vh is 1% of viewport height. In a 1280 by 800 CSS-pixel viewport, 50vw is 640px and 10vh is 80px. 100vw can include scrollbar width, producing horizontal overflow where 100% of the parent would fit.
max-width: 65ch gives a text column a font-related width. It is roughly a reading-length measure, not a promise that every line has exactly 65 characters.
Combine units with a calculation
width: calc(100% - 40px); subtracts a fixed amount from a relative size. Keep spaces around + and -; calc(100%-40px) is invalid. Browsers compute font-relative lengths into pixels, while container-size percentages resolve during layout. Developer tools show the resulting sizes so you can check both the reference and the arithmetic.
Key Takeaways
- Join numbers directly to their units; zero can stand alone.
emuses the parent for font size and the element itself for other lengths.remfollows the root, avoiding nested font-size compounding.- Percentage references depend on the property; percentage padding uses container width.
- Viewport units follow the window;
chfollows the font. - Use spaces around addition and subtraction inside
calc().
5Measure boxes and control spacing
Every visible element takes up space as a box. The width you write may describe only the content or the whole border box, and margins add another layer of spacing outside it. Display type changes which size and spacing properties take effect. Learn to calculate a box before changing its dimensions, then explain common surprises such as an overflowing full-width card, an inline link that ignores width, or two vertical margins that combine.
5.1 Content, padding, border and margin
From inside out, a box has content, padding, border and margin. Content holds text, images or child elements. Padding creates breathing room around that content. The border surrounds the padding; margin separates the border box from its neighbors.
A background fills content and padding and extends under the border, but never colors the margin. Use padding when the space should be part of a colored card. Use margin for space outside it. Margins can be negative; padding cannot.
Read the spacing shorthands
margin, padding and border-width accept one to four values:
| Values | Sides set |
|---|---|
10px | All four |
10px 20px | Top/bottom, then left/right |
10px 20px 30px | Top, left/right, bottom |
10px 20px 30px 40px | Top, right, bottom, left |
The four-value order runs clockwise from the top. Use longhands such as padding-left to change just one side after the shorthand. Do not read the second value of a two-value form as the bottom: it sets both horizontal sides.
Calculate the default content box
.card {
width: 300px;
padding: 20px;
border: 5px solid;
margin: 10px;
}
The initial box-sizing value is content-box. The declared 300px width covers only the content. Add 20px padding twice and 5px border twice: the border box is 350px wide. Add the two 10px margins to get 370px of horizontal space.
Height works the same way when it is explicitly sized, but text often needs a box that can grow. Leaving height: auto avoids trapping changing content in a fixed height.
Include padding and border in the width
With box-sizing: border-box, the same declared width includes padding and border. The border box stays 300px; subtract 40px padding and 10px border to find a 250px content area. Margins remain outside, giving 320px of horizontal space.
A common reset applies this model to elements and their generated parts:
*, *::before, *::after { box-sizing: border-box; }
box-sizing does not inherit automatically, so the rule selects the boxes directly.
A full-width child makes the difference easy to see. In a 600px container, width: 100%; padding: 0 20px; gives a 640px border box under content-box sizing, before any border. With border-box sizing, the same 600px declared width includes the padding and fits the container.
Let content fit safely
min-height sets a lower bound while allowing growth. max-width: 800px lets an auto-width block shrink in a narrow container while preventing it from becoming wider than 800px.
If content exceeds a fixed box, overflow controls the result: visible spills out, hidden clips, scroll requests scrollbars and auto provides scrolling when needed. pre { overflow: auto; } gives a long code line its own scrolling area. Clipping is a poor fix for text that readers still need; first check whether the fixed size is necessary.
Use the Computed panel's box diagram to compare the browser's content, padding, border and margin values with your calculation.
Key Takeaways
- Padding is inside the border; margin is outside and stays transparent.
- Content-box width excludes padding and border.
- Border-box width includes padding and border, but never margin.
- Spacing shorthands run clockwise from the top, with shorter forms sharing sides.
- Use flexible height and size limits to accommodate changing content.
overflowcontrols content that exceeds the box.
5.2 Display, centering and collapsed margins
Display type determines how a box joins its surroundings. A block normally starts a new line and fills available width when width is auto. An ordinary inline box flows within text and is sized by its content. Inline-block keeps the inline position while accepting explicit dimensions.
Choose the behavior you need
| Display | Width and height | Spacing behavior |
|---|---|---|
block | Apply | Margins and padding separate boxes |
Ordinary inline | Do not size the box | Horizontal spacing affects nearby text |
inline-block | Apply | Vertical and horizontal spacing affect surrounding layout |
For ordinary inline elements such as span and a, top and bottom margins have no effect. Vertical padding and borders are drawn but do not push neighboring lines apart, so they can overlap them. Horizontal padding, borders and margins do take space along the line.
nav a {
display: inline-block;
padding: 8px 16px;
}
These links remain in a line while their padded boxes reserve vertical space. display: block would give each link its own line. Images are a special inline case: they accept width and height. Their default baseline alignment can leave a small gap below for letter descenders; img { display: block; } removes that baseline gap.
display: none removes the box and its space, and removes it from screen-reader reading. visibility: hidden hides it while preserving its space.
Center a box or center its contents
.page {
max-width: 960px;
margin: 0 auto;
}
On a wider container, the block stops growing at 960px and the two horizontal auto margins split the remaining space equally. A block that fills the container has no leftover horizontal space to split. Auto margins do not center an ordinary inline box, and vertical auto margins in normal block flow resolve to zero.
text-align: center does a different job: it centers inline content inside a block. A centered paragraph box can still have left-aligned text; a full-width paragraph can have centered text without becoming a narrower centered box.
Recognize collapsing vertical margins
In normal block flow, adjoining top and bottom margins can collapse. Two positive margins become the larger one. A heading with 24px bottom margin followed by a paragraph with 16px top margin has a 24px gap, not 40px. Horizontal margins do not collapse.
With positive and negative margins, combine the largest positive with the most negative: 20px and −8px become 12px. If all are negative, the most negative wins. An empty box without separating content, height, border or padding can collapse its own top and bottom margins.
A first child's top margin can also collapse through a parent with no separating border, padding or earlier content. The space then appears outside the parent's background. Add parent padding or a border, or remove the child's top margin. Similar conditions allow a last child's bottom margin to collapse; a parent height or minimum height can prevent that bottom case.
Inline-block boxes do not collapse margins, nor do flex/grid items or floated and absolutely positioned boxes. A simple text-spacing pattern sets top margins to zero and uses bottom margins, with padding for space inside containers.
Key Takeaways
- Ordinary inline boxes ignore set width and height; inline-block boxes accept them.
- Auto horizontal margins center a narrower block;
text-aligncenters its inline contents. - Adjacent positive vertical block margins can collapse to the larger value.
- Parent padding can separate a first child’s margin from the parent’s margin.
display: noneremoves space;visibility: hiddenpreserves it.
6Style readable text and finished surfaces
Fonts, line spacing and link states shape how comfortably a reader can use a page. Backgrounds, borders and shadows then distinguish its boxes without changing their meaning. Build text styles with fallbacks, keep essential content in HTML, and choose decoration that supports the content. The same box and cascade rules still apply: a shorthand can reset a font weight, a border can add width, and a focus outline can show a state without moving anything.
6.1 Font stacks and web fonts
A font choice is a preference with a fallback plan. Devices have different installed fonts, and a downloaded font may arrive after the text. A font stack keeps the page readable while preserving a suitable style.
Build a stack
body {
font-family: "Helvetica Neue", Arial, sans-serif;
font-size: 1rem;
}
The browser tries the family names in order and uses an available font. Quote names containing spaces. Leave generic families unquoted: "sans-serif" asks for a named font with that exact name; sans-serif asks the browser for a suitable generic font.
Generic choices include serif, sans-serif, monospace, cursive, fantasy and system-ui. The last uses the system's interface font. Fonts often called web-safe, such as Arial, Georgia and Verdana, are common, not guaranteed. A generic fallback still belongs at the end.
font-size accepts lengths, percentages and size keywords. With a 16px root, 1rem gives 16px and 2.5rem gives 40px. Relative sizes can follow reader settings.
Set weight, style and shorthand carefully
font-weight: normal equals 400; bold equals 700. Values such as 300 and 600 request other weights when the font provides them. If a requested weight is absent, the browser chooses an available one or may synthesize bold. With only 400 and 700 loaded, requesting 300 uses 400. bolder and lighter are relative to the parent.
font-style: italic requests an italic face; normal removes that style. The font shorthand needs both size and family:
blockquote {
font: italic 700 1.125rem/1.6 Georgia, serif;
}
Optional style, variant and weight come before size. A slash attaches line height to size, and family comes last. Omitting size or family invalidates the shorthand. Other omitted font settings reset: font: 1rem Arial, sans-serif; resets a previous bold weight to normal.
Load a font file
@font-face {
font-family: "Inter";
src: url("fonts/inter-regular.woff2") format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
body { font-family: "Inter", Arial, sans-serif; }
@font-face assigns a CSS family name to a file. Use that declared name in the stack, not the file name. Relative file paths start from the stylesheet's location. WOFF2 is a compressed format supported by current browsers.
Static fonts generally need separate files and rules for each weight and style. Variable fonts can hold a weight range in one file. Load the files the design actually uses. font-display: swap displays a fallback immediately and replaces it when the web font becomes available.
A font service can supply an HTML link and the family declaration; self-hosting avoids a font request to a third-party server. Check that the font license permits website use. If the font looks wrong, inspect the rendered font and the file request. A misspelled CSS family silently falls back, so readable text alone does not show that the intended font loaded.
Key Takeaways
- Write a font stack with an unquoted generic fallback.
- Font weight depends on the faces or ranges actually available.
- The
fontshorthand requires size and family and resets omitted settings. @font-facedefines a family name and the file that supplies it.font-display: swapkeeps text visible in a fallback while a web font loads.
6.2 Line spacing, lists and link states
Text styling needs to survive changes in size, content and input method. Begin with line spacing and readable widths, then add list and link details that tell readers how the content works.
Let line height follow each font size
Use a unitless line height such as line-height: 1.5. With 16px body text it creates 24px lines. Children inherit the number, so a 32px heading gets 48px lines. A parent value of 1.5em or 150% instead computes to 24px there, and a child can inherit that fixed 24px line height even when its own text is larger. The default normal depends on the font and is often around 1.2.
body { font: 1.125rem/1.6 Georgia, serif; color: #222222; }
h1 { font: 700 2.25rem/1.2 Arial, sans-serif; }
p { max-width: 65ch; }
At a 16px root, the body text is 18px with 28.8px lines; the heading is 36px with 43.2px lines. The paragraph limit prevents very long lines on a wide screen.
text-align positions inline content within a block. Values include left, right, center, justify, start and end; start/end follow writing direction. It does not move the block itself. Justification in narrow columns can create large word gaps.
Change presentation without rewriting text
text-transform can show uppercase, lowercase or capitalized words without changing the HTML text. letter-spacing, word-spacing and text-indent control different kinds of space. text-shadow: 1px 1px 2px rgb(0 0 0 / 0.5); gives horizontal offset, vertical offset, blur and color.
text-decoration adds underlines, overlines or line-through marks. It can also set style and color, as in underline wavy crimson. Thickness and underline offset refine a line. Readers expect underlined text to be a link, so reserve that cue accordingly.
Style lists without leaving accidental indentation
list-style-type chooses markers such as disc, square, decimal or lower-alpha. list-style-position: outside keeps markers outside the text block; inside puts them into the first line, so wrapped lines can begin beneath the marker. list-style-image provides an image marker, and li::marker can color the marker alone.
For a plain navigation list, use .menu { list-style: none; margin: 0; padding: 0; }. Removing markers alone leaves the list's default start padding. list-style: square inside is a shorthand combining marker settings.
Keep links visible during use
Order equal-specificity state rules as link, visited, focus, hover, active. A link can be both visited and hovered; source order decides their competing color declarations. :active means during activation, not the current page.
Keep links recognizable by more than color alone, commonly an underline in running text. Give keyboard focus a clear indicator:
a:focus-visible {
outline: 3px solid #f2a900;
outline-offset: 2px;
}
Do not remove the focus outline unless another visible focus style replaces it. An outline takes no box-model space, so this cue does not shift the surrounding text.
Key Takeaways
- Unitless line height passes a multiplier that follows each child’s own font size.
text-alignmoves inline content inside a block, not the block itself.- Text transform changes appearance without changing the HTML wording.
- Removing list markers does not remove the list’s default padding.
- Link states can overlap; keep a recognizable link and visible keyboard focus.
- Outlines show focus without changing box dimensions.
6.3 Background images, scaling and layers
A background sits behind a box's content. Its color fills the content and padding and extends under the border; the margin stays transparent. An image is drawn above the background color, so a color can provide a dependable surface while the image loads.
Resolve the path from the stylesheet
.hero {
background-color: #1a2b3c;
background-image: url("../images/hero.jpg");
}
If the CSS is in css/styles.css and the image is in the site's top-level images folder, .. moves out of css before entering images. A CSS image URL starts from the CSS file, unlike the stylesheet link, which starts from the HTML file. Check the image request if a valid rule displays only its fallback color.
Backgrounds are decoration. A screen reader does not announce them as images. Put an informative image into HTML with meaningful alternative text. A fallback color close to the image's main tone also helps text stay readable if the image is slow or missing.
Control repetition, scale and position
Images initially repeat at their natural size. no-repeat uses one copy; repeat-x makes a row and repeat-y a column. space distributes whole tiles with gaps, while round adjusts tiles to fit a whole number.
| Size | Result |
|---|---|
cover | Fill the whole box, preserving proportions; cropping may occur |
contain | Fit the entire image, preserving proportions; gaps may remain |
200px 100px | Set both dimensions explicitly |
50% auto | Set relative width and preserve the image's ratio |
For an 800px by 400px box and a square 1000px image, cover scales the image to 800px square, leaving 400px of image height outside the box. Contain scales it to 400px square; with no-repeat, 400px of box width remains uncovered. Setting only contain does not turn repeating off.
The initial position is top left. background-position: center centers an image; right 20px bottom 10px offsets it from those edges. A horizontal value comes first. Center plus cover keeps the middle visible when cropping is necessary.
Generate and stack images
A gradient is an image, so put it in background-image:
background-image: linear-gradient(to right, #1e90ff, #8a2be2);
The first color is on the left and the second on the right. Angles and positioned stops give more control; radial-gradient(circle, white, steelblue) spreads outward from the center. A gradient in background-color is invalid.
Separate multiple images with commas; the first is on top. A translucent black gradient listed before a photo can darken the image without fading the text.
Use the shorthand deliberately
background: url("hero.jpg") center / cover no-repeat #1a2b3c; combines an image, position, size, repetition and color. Size follows position after a slash. Only the final layer can have a color. Omitted background settings reset, so a later background: white; removes a previous image.
background-attachment initially uses scroll, moving with the element as the page scrolls. fixed keeps the background attached to the viewport. Test the actual box and text after adding decoration; scaling and cropping should not hide information readers need.
Key Takeaways
- CSS image paths are resolved from the stylesheet’s location.
coverfills and may crop;containfits the whole image and may leave gaps.- Background images repeat unless repetition is changed.
- Gradients are images, and the first background image is drawn on top.
- The background shorthand uses a slash between position and size and resets omitted settings.
- Put informative images in HTML; backgrounds serve as decoration.
6.4 Borders, rounded corners, outlines and shadows
A border forms part of the box model. An outline or shadow is drawn around the box without reserving additional space. Choosing between them changes both the appearance and the sizing behavior of a style.
Give a border a style
.note {
border: 1px solid #cccccc;
border-left: 4px solid crimson;
padding-left: 12px;
}
The shorthand sets width, style and color; these parts may appear in any order. The border style initially is none, so setting only width and color does not produce a visible border. Styles include solid, dashed, dotted, double, groove, ridge, inset and outset, as well as none and hidden.
If width is omitted it uses medium, commonly 3px in current browsers. If color is omitted it uses currentColor, matching the element's text. Side shorthands such as border-top and longhands such as border-left-color let you add an exception after a general border. For example, border-top: none removes only the top edge after a four-sided border declaration.
Under content-box sizing, a 2px border on each side adds 4px to width and height. Increasing border width on hover can therefore shift nearby content. Keep the border width stable and change its color, or use an outline for a cue that takes no space. Under border-box sizing, a thicker border instead uses more of the declared box's interior.
Round corners in a predictable order
border-radius: 8px rounds all corners even when the border itself is invisible. With four values the order is top left, top right, bottom right, bottom left. Two values apply to opposite corner pairs: the first to top left/bottom right, the second to top right/bottom left.
border-radius: 50% makes a square box circular and a rectangle elliptical. Its own background is clipped to that rounded edge. The radius does not itself crop overflowing child content; that is a separate overflow decision. Radius does not add to the box's measured dimensions.
Add a focus line or depth
.link:focus-visible {
outline: 3px solid navy;
outline-offset: 2px;
}
An outline is drawn outside the border and takes no layout space. Its offset creates a gap from the border. It is a useful focus cue because it can appear without moving neighboring boxes.
box-shadow: 0 2px 6px rgb(0 0 0 / 0.2); gives a horizontal offset of zero, a 2px downward offset, 6px blur and a translucent black color. An optional spread value comes after blur. inset draws the shadow inside; comma-separated values add multiple shadows. Shadows follow rounded corners and do not add box-model space.
Check one finished card
A card with width: 280px; padding: 16px; border: 1px solid #dddddd; is 314px wide in content-box sizing. Add twice 16px and twice 1px to 280px. Under border-box sizing it stays 280px, leaving 246px for content. A 12px corner radius and a soft shadow change neither calculation. They change the drawn edge, not the dimensions used to place other boxes.
Key Takeaways
- A visible border needs a style such as
solid. - Borders participate in box sizing; outlines and shadows reserve no extra layout space.
- Corner radii run clockwise from the top left, with shorter forms pairing corners.
- A 50% radius makes a square circular and a rectangle elliptical.
- A box shadow lists horizontal and vertical offsets, then optional blur and spread, then color.
CSS examples
1Make a stylesheet work and inspect it
10 steps
- 1IntroductionFrom meaningful HTML to a styled page
A heading and paragraph already have browser-supplied styles. You will give them a chosen font and color, then follow the result back to the CSS.
The first job is a reliable connection between files. After that, a rule needs to match the element, contain a valid declaration and win the relevant property. Treat those as separate checks when the page does not change.
- 2ExampleConnect an external file
Suppose
index.htmlsits beside a folder namedcss, which containsstyles.css. Add this inside the HTMLhead:<link rel="stylesheet" href="css/styles.css">The path starts at the HTML file and enters the CSS folder. Saving rules in that external file lets other pages link to the same design. A misspelled path can leave the HTML readable while none of these author styles load.
- 3ExplanationWrite and read one rule
Put this in the linked stylesheet:
p { color: navy; font-size: 18px; }pselects paragraphs. The braces hold two declarations, each pairing a property with a value. The semicolons separate the declarations. Reload the page: a matching paragraph receives navy text and an 18px font size unless a higher-priority declaration changes one of those properties. - 4ChallengeRepair one invalid value
A rule says
p { font-size: 18 px; color: teal; }. Predict the effect and repair the size declaration.---reveal---
The teal color can apply, but the size declaration is invalid because a length's number and unit must touch. Change it to
font-size: 18px;. The browser skips the invalid declaration, not the whole block, so a working color is not evidence that the size value was accepted. - 5Key InsightNotice what a shorthand clears
These declarations do not keep the photo:
background-image: url("sky.jpg"); background: lightblue;The shorthand resets background properties it leaves out, including the image. Write a general shorthand first and the longhand exception after it when both should survive. This explains a valid-looking change that disappears even when the path and selector are correct.
- 6ConnectionKeep useful browser defaults
Large headings, paragraph gaps and list markers are already present because of the user-agent stylesheet. Your rules modify that starting point.
body { margin: 0; }removes a specific default gap. Resetting every margin and padding also removes useful paragraph spacing and list indentation. Choose the HTML heading level for meaning, then change its font size; choosing a smaller heading level just for its appearance changes the document structure. - 7TipInspect a property before guessing
Right-click the paragraph and choose Inspect. Look for its rule in Styles. An absent rule suggests a matching or loading problem; a warning suggests invalid CSS; a crossed-out declaration lost the cascade.
Computed shows the resulting values and the box diagram. Test a change there, then save it in your stylesheet. An inspection edit alone is temporary and disappears when the browser reloads the saved files.
- 8ChallengeExplain a surviving list gap
A navigation list has
list-style: none, yet its items remain indented. The rule is valid and not crossed out. What should you inspect and change?---reveal---
Inspect the list's padding. Removing markers does not remove its default start padding. Reset that padding, commonly with
padding: 0, to remove the indentation; add deliberate spacing afterward if the design needs it. The marker setting and box spacing are separate properties. - 9ChallengeFollow the failed change
A page still shows default paragraph styling. The Network panel reports a failed request for
styles.css, while the actual file iscss/styles.css. What should you fix first, and how should you check the result?---reveal---
Correct the HTML stylesheet link to
css/styles.css. Reload, confirm the request succeeds, then inspect the paragraph for its matching rule. Raising selector specificity cannot help while the stylesheet containing that selector is not loading. - 10RecapA dependable debugging route
Start with a valid HTML doctype and a correctly linked stylesheet. A rule then needs a matching selector and valid property values. Shorthands can reset earlier longhands even when every declaration is valid.
Use Network for loading, Styles for matching and priority, and Computed for final dimensions. Preserve successful experiments in the CSS file so they survive reload. Browser defaults remain part of the explanation whenever your rules leave a property alone.
2Read selectors against the HTML tree
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDescribe the intended match
- 2ExampleReuse one class across elements
- 3ChallengeA space changes the target
- 4TipShare rules without requiring nesting
- 5ExplanationMatch attributes and current states
- 6ExampleCount siblings, not paragraphs alone
- 7ChallengeChoose a marker without replacing text
- 8ExplanationFind direct children in a nested list
- 9ExampleTrace the two sibling relationships
- 10ChallengeKeep the same parent in view
- 11ChallengeCombine location with state
- 12RecapRead the selector as a matching test
3Trace a conflict from priority to inheritance
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionOne element can have several winners
- 2ExplanationFilter before comparing
- 3ExampleResolve an inline color
- 4Key InsightUse layers before stronger selectors
- 5ChallengeName the deciding stage
- 6ExampleCount selector parts by column
- 7ExplanationHandle functional selectors
- 8ChallengeCompare without adding columns
- 9ConnectionLet text inherit and boxes stay separate
- 10ExplanationChoose the reset you intend
- 11ChallengeSeparate a child from its parent’s selector
- 12ChallengeFollow the complete decision
- 13RecapGive each decision its own job
4Choose a color and calculate a relative size
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionRead the reference behind the value
- 2ExampleDecode three color channels
- 3Key InsightKeep solid text over a translucent fill
- 4ChallengeCheck the right threshold
- 5ExampleCompute text size before its spacing
- 6ConnectionAvoid repeated growth in nested text
- 7ExplanationGive percentages the right reference
- 8ChallengeApply two different references
- 9ChallengeConnect font size to contrast
- 10RecapChoose what the value should follow
5Measure a card and explain its gaps
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionStart at the content and work outward
- 2ExplanationName the four layers
- 3ExampleCalculate a content-box card
- 4ExampleSwitch what the width includes
- 5ChallengeFix a full-width overflow
- 6ConnectionMake a link accept dimensions
- 7ExampleSplit the remaining horizontal space
- 8Key InsightCombine vertical margins
- 9ChallengePredict a mixed-sign gap
- 10ChallengeRecalculate the centered card
- 11RecapMeasure the layer that causes the problem
6Build readable text and a finished card
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive each visual choice a purpose
- 2ExplanationChoose a dependable font stack
- 3ExampleLoad a face and preserve visible text
- 4ChallengeCatch a font shorthand reset
- 5ExampleKeep line spacing proportional
- 6TipKeep menus and links understandable
- 7ChallengeSeparate the block from its contents
- 8ExampleFollow a background path
- 9ExampleScale a square photo into a wide box
- 10Key InsightLayer a tint above a photo
- 11ChallengeProtect the complete photograph
- 12ExplanationDraw an edge without moving its neighbors
- 13ChallengeRound the box, keep the measurement
- 14ChallengeFinish a stable interactive card
- 15RecapConnect decoration to the underlying rules
CSS practice questions
Set 1: Read rules and predict simple results10 Practice Questions
Question 1 of 10
color: 18px; padding: 12px;. What happens to these declarations?Show answerHide answer
18px is a length, so it is not a valid value for color; the browser ignores that declaration. The padding value is valid and still applies. A bad value does not invalidate every declaration in the same block, which is why rejecting both declarations would lose a working style.Question 2 of 10
Show answerHide answer
Question 3 of 10
class="panel featured". What selector requires both class words on that same element?Show answerHide answer
Question 4 of 10
h2, then two p elements. What does article p:first-child select?Show answerHide answer
:first-child asks whether the paragraph is the first element child of its parent. The heading occupies that position, so neither paragraph matches. Selecting the first paragraph would confuse first child with first of type; p:first-of-type would express that different request in this article.Question 5 of 10
.badge { color: teal; } followed by .badge { color: maroon; }. What color wins?Show answerHide answer
Question 6 of 10
.panel > a:hover?Show answerHide answer
a adds one in TYPE. The child combinator adds nothing, so the result is 0-2-1. Counting the combinator as another type would incorrectly give 0-2-2; relationship symbols carry no specificity weight.Question 7 of 10
#4bd?Show answerHide answer
#44bbdd. Appending zeros to make #40b0d0 changes the channel values, so it creates a different color instead of expanding the short form.Question 8 of 10
width: 240px; padding: 12px; border: 3px solid; margin: 8px;. What is its border-box width?Show answerHide answer
Question 9 of 10
Show answerHide answer
sans-serif remains available when the named fonts are absent. Quoting that generic makes it a literal font name. The stack can then lose its intended category fallback even though the declaration still parses.Question 10 of 10
section has font-size: 20px; line-height: 1.4;. Its h2 child has font-size: 1.5em and no line-height declaration. What are the heading’s font size and line height?Show answerHide answer
Set 2: Apply selectors, spacing and decoration10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
/site/pages/team.html; the stylesheet is /site/css/theme.css. What relative href reaches the stylesheet?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
section contains an h3, a p, an aside, then another p. What does h3 ~ p select within that section?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
#article { color: olive; }, and its paragraph child matches p { color: purple; }. What color does the paragraph use?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
style="color: coral;" and matches .notice { color: indigo !important; } in author CSS. What color is used?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
font-size: 1.5em; padding: 0.5em;. How much padding is set on each side?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
width: 180px has no sizing effect. What display value keeps it inline-level while allowing that width?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
width: 260px; padding: 18px; border: 2px solid;. How wide is its content area?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
background-color: linear-gradient(white, navy);. Why is the gradient not shown?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
border-width: 4px; border-color: teal; and no other border declarations. Why is no border visible?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
@layer base, widgets;. Base contains #info { color: teal; }; widgets contains .card { color: maroon; }. An unlayered rule p { color: navy; } also matches <p id="info" class="card">. What color wins?Show answerHide answer
Save this lesson to see this answer.
Set 3: Trace values through real page structures10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
href="manual.PDF". What selector matches a PDF ending regardless of letter case?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
.alert.urgent does not match <p class="alert"><span class="urgent">Update</span></p>. What selector targets the urgent span only when it is inside an alert?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
div class="tools" contains a direct ul with link A inside an li, plus a section containing another ul with link B. Both links are hovered. What does .tools > ul a:hover match?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
#menu a and .menu a.selected. Both match one link. Which selector has greater specificity?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
div { display: initial; }. What display value does the div get from that declaration?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
background-color: rgb(0 0 0 / 0.5); color: white; over a photo. A developer replaces the alpha background with solid black and adds opacity: 0.5 to the caption. What changes?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
padding-top: 10% resolve to on its child?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
background-size: contain; background-position: center;?Show answerHide answer
Save this lesson to see this answer.
Set 4: Resolve competing styles and changing boxes10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
h2, p..lead, blockquote { color: teal; } changes none of these elements. What explains the result?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
section contains <h2>News</h2><aside><p>A</p></aside><p>B</p><p>C</p>. What text is selected by h2 + p and h2 ~ p, respectively?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
@layer foundations, details;. Foundations has .flag { color: teal !important; }; details has #notice { color: purple !important; }; an unlayered rule has p { color: navy !important; }. All match one paragraph. What color wins?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
width: 100%; padding: 0 15px; in a 480px-wide content area, with no borders or margins. How wide is its border box?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
width: 320px; padding: 18px; border: 2px solid; with content-box sizing. It must stay 360px wide after switching to border-box and raising padding to 24px. What declared width and content width result?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
font-weight: 700; font-style: italic;, then font: 1.25rem/1.4 Arial, sans-serif;. What weight and style apply after the shorthand?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
list-style: none; but its items are still indented. What additional rule removes the default indentation?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Diagnose and explain unfamiliar combinations10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
width: 160px is valid and not crossed out, but the span is still only as wide as its text. What explains this?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
li:nth-child(3n+2)?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
<section id="main"> matches :where(#main) a { color: teal; }, :is(#spare, section) a { color: purple; }, then .chosen:hover { color: navy; }. It has class chosen and is hovered. What color wins?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
color: maroon; background-color: beige;. Its child has color: unset; background-color: unset; and no other relevant styles. What are the child’s own color and background values?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
width: calc(100% - 4rem); padding: 1em; border: 2px solid; font-size: 1.5rem;. What is the child’s content width?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
width: 320px; margin: 0 auto; text-align: center;. What horizontal margins and text alignment result?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
@font-face { font-family: "Lumen Sans"; src: url("fonts/lumen-regular.woff2") format("woff2"); }. What name should a font stack use to request this face?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
a:hover { color: teal; } first and a:visited { color: purple; } second. A visited link is hovered. What change makes its hovered color teal while preserving a purple visited color when not hovered?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
/site/index.html links /site/css/main.css. That CSS uses background-image: url("images/banner.jpg");, but the image is /site/images/banner.jpg. A later rule also sets background: navy;. What repair keeps navy behind the image?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
border-radius: 50%. What rounded shape does its background make?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Alpha
Attribute selector
a[href$=".pdf" i] can style document links even when the file ending is uppercase.Auto margin
B
Background image
Background layer
Background position
Background size
Block box
Border
Border radius
Box shadow
Box sizing
C
Calc function
calc() function combines compatible CSS values in an expression, allowing a length to mix relative and absolute amounts.calc(100% - 40px) leaves a fixed amount out of a container-relative width, with spaces around minus.Cascade
Cascade layer
Ch unit
ch is a font-relative length based on the advance width of the zero character, often used to limit the width of text columns.max-width: 65ch follows the font size without promising exactly 65 letters per line.Child
.menu > li leaves out items whose parent is a separate nested list inside the menu.Class selector
.notice matches both a plain notice and an element with class="card notice".Compound selector
p.note reaches a paragraph with the note class, while p .note asks for a descendant.Computed value
em font size becomes pixels while a width percentage depends on layout.Content area
Contrast ratio
CSS
CSS pixel
Current color
currentColor keyword represents the element's own text color when another color-bearing property needs a matching value.currentColor changes with the text color when a hover rule updates only color.D
Declaration
color: navy;, the declaration sets text color, and the semicolon separates it from the next setting.Descendant
nav a reaches a navigation link even when a list and a list item sit between it and the nav.E
Em unit
em is a font-relative length using the parent's font size for font-size and the element's own font size in other properties.2em padding becomes 40px instead of following the parent again.F
Focus-visible state
a:focus-visible before activating it.Font stack
sans-serif still gives a suitable font on a device without the named fonts.Font-face rule
@font-face rule assigns a CSS family name and face characteristics to a font resource that can be used in a font stack.G
Generated content
::after needs a content value; essential instructions stay in the HTML.Generic font family
sans-serif makes it a literal font name and removes its role as the stack's generic fallback.Gradient
H
Hex color
#3ac gives #33aacc because each digit becomes a repeated pair for its own channel.HSL color
I
ID selector
#site-header can be harder to override later than one using a reusable header class.ID-CLASS-TYPE triple
a[href]:hover has the triple 0-2-1, with the attribute and hover counted as CLASS.Important declaration
!important, giving it priority over normal declarations of the same origin.p.Inherit keyword
inherit keyword explicitly gives a property its parent's computed value, even when that property normally does not inherit.font: inherit on controls can replace their browser-assigned font with the surrounding text font.Inheritance
Initial keyword
initial keyword selects a property's starting value from the CSS specification, independent of the HTML element's default rule.display: initial to a div gives inline display even though the browser normally makes it block.Inline box
width: 200px while it remains inline.Inline-block box
L
Line height
Link state
List marker
::marker.M
Margin
Margin collapsing
N
Next-sibling combinator
+, selects a matching element immediately after another element when both share the same parent.h2 + p reaches an opening paragraph but stops matching when an aside appears between them.O
Outline
Outline offset
Overflow
overflow: auto can scroll its long line without making the whole page wider.P
Padding
Percentage
Pseudo-class
:checked pseudo-class can select a checkbox whose current checked state is not represented by a class.Pseudo-element
li::marker can color list bullets while leaving the list item text at its existing color.R
Rem unit
rem is a length relative to the root element's font size, providing a shared reference across nested elements in the page.1.25rem keep the same text size when they share an unchanged root size.Reset
Revert keyword
revert keyword rolls a property back past the current style origin, exposing an applicable value from a lower origin.display: revert can restore a div's normal browser-assigned block display.Revert-layer keyword
revert-layer keyword rolls a property's value back past the current cascade layer so a lower-priority source can supply it.RGB color
rgb().rgb(30 144 255) gives the same channel amounts as the six-digit hex value #1e90ff.S
Selector list
h1, h2, h3 can give all three heading levels one font family without requiring nesting.Shorthand property
background: white; can remove a photo previously assigned through background-image.Sibling
Source order
Specificity
Standards mode
<!DOCTYPE html> first avoids the legacy behavior that can affect a page in quirks mode.Structural pseudo-class
p:first-child.Style origin
Styles panel
Stylesheet
css/styles.css lets a page load its styling from the file in the neighboring folder.Subsequent-sibling combinator
~, selects matching later siblings of an element, allowing other siblings in between.h2 ~ p can reach two paragraphs separated by an aside when all share the heading's parent.T
Text alignment
Text decoration
Text transform
Type selector
p can establish paragraph spacing across the page without assigning a class to each one.U
Universal selector
*, matches every element but contributes zero specificity, making it useful in broad defaults and resets.* can reset margins, while a class selector can later supply spacing with greater specificity.Unset keyword
unset keyword follows normal inheritance for an inherited property and uses the initial value for a non-inherited property.unset on color can preserve a parent's text color, while using it on margin removes a local margin.User-agent stylesheet
V
Variable font
Viewport unit
vw using width and vh using height as the reference.10vh is 80px when the viewport height is 800 CSS pixels, even inside a shorter container.W
Web font
Z
Zero-specificity selector
:where() also removes the weight of its arguments.:where(#main) p remains easy to override because only the paragraph contributes a type point.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.