CSS Basics

Learn to style web pages with CSS. Write rules and connect a stylesheet, start from the browser's default styles, and select exactly the elements you want. Predict which style wins when rules conflict through the cascade, specificity and inheritance. Write colors and choose units, size and space elements with the box model, and style fonts, text, lists, links, backgrounds and borders.

BeginnerLesson 4 of 8 in Web Development Basics Course

What you will learn

  1. 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 page
      Read 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 them
      Recognize 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.
  2. 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 ID
      Select 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 elements
      Use 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 page
      Select elements by their relationship to other elements in the HTML tree: anywhere inside, directly inside, right after or somewhere after another element.
  3. 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 declaration
      Apply the cascade's steps (origin and importance, specificity, then order of appearance), and use inline styles, !important and cascade layers with care.
    • Calculate and compare specificity
      Score 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 keywords
      Know which properties pass from parent to child, use inheritance to write less CSS, and control it with inherit, initial, unset and revert.
  4. 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() and hsl(), add transparency, and check that text contrasts enough with its background.
    • Choose lengths and units
      Use pixels, em, rem, percentages and viewport units correctly, know what each relative unit is measured against, and combine units with calc().
  5. 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 margin
      Name 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 boxes
      Predict how block, inline and inline-block boxes take up space, center a block with automatic margins, and recognize when vertical margins collapse.
  6. 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 fonts
      Write font stacks with fallbacks, set size, weight and style, use the font shorthand, and load a custom font with @font-face.
    • Style text, lists and links for readability
      Set line height, alignment, decoration, case and spacing, change list markers and indentation, and give links clear, accessible states.
    • Add background colors, images and gradients
      Fill boxes with colors, images and gradients, control how background images repeat, scale and sit, and write the background shorthand.
    • Draw borders, rounded corners, outlines and shadows
      Write border shorthands for all or single sides, round corners with border-radius, and add outlines and shadows without changing the layout.

CSS study guide

6 chapters

1

Connect 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.
2

Select 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
SelectorMatches
pEvery paragraph
.warningEvery element with the class warning
#site-headerThe 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.intro requires both conditions on one element; p .intro describes 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.

PatternMeaning
[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-child counts all element siblings, while :first-of-type counts the same element type.
  • Link states can overlap, so competing state rules need a deliberate order.
  • ::before and ::after need content; 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
CombinatorExampleTarget
Spacenav aAny link anywhere inside a nav
>.menu > liAn li directly inside .menu
+h2 + pA paragraph immediately after an h2, with the same parent
~h2 ~ pAny 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.
3

Work 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 originPriority
Author: the site's CSSHighest of these three
User: a reader's custom stylesBetween author and browser
User agent: browser defaultsLowest

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.
  • !important changes 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.

ColumnCount each of these
IDID selectors such as #menu
CLASSClasses, attribute selectors and ordinary pseudo-classes
TYPEType 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
KeywordEffect
inheritTake the parent's computed value
initialUse the CSS property's initial value
unsetInherit an inherited property; initialize a non-inherited one
revertRoll back the current origin's styles
revert-layerRoll 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.
  • initial means the CSS initial value; revert can restore browser element defaults.
  • unset chooses inheritance or initialization according to the property.
  • revert-layer removes the current layer from that property decision.
  • A parent underline is drawn through inline descendants without being inherited.
4

Write 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, while hsl() gives hue, saturation and lightness.
  • Alpha in a background color affects that color; opacity fades the whole element.
  • currentColor follows 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
UnitReference
pxA CSS reference pixel
em in font-sizeThe parent's font size
em in spacing and other lengthsThe element's own font size
remThe root element's font size
%A reference determined by the property
vw, vhViewport width or height
chThe 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.
  • em uses the parent for font size and the element itself for other lengths.
  • rem follows the root, avoiding nested font-size compounding.
  • Percentage references depend on the property; percentage padding uses container width.
  • Viewport units follow the window; ch follows the font.
  • Use spaces around addition and subtraction inside calc().
5

Measure 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:

ValuesSides set
10pxAll four
10px 20pxTop/bottom, then left/right
10px 20px 30pxTop, left/right, bottom
10px 20px 30px 40pxTop, 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.
  • overflow controls 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
DisplayWidth and heightSpacing behavior
blockApplyMargins and padding separate boxes
Ordinary inlineDo not size the boxHorizontal spacing affects nearby text
inline-blockApplyVertical 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-align centers 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: none removes space; visibility: hidden preserves it.
6

Style 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 font shorthand requires size and family and resets omitted settings.
  • @font-face defines a family name and the file that supplies it.
  • font-display: swap keeps text visible in a fallback while a web font loads.

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-align moves 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.

SizeResult
coverFill the whole box, preserving proportions; cropping may occur
containFit the entire image, preserving proportions; gaps may remain
200px 100pxSet both dimensions explicitly
50% autoSet 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.
  • cover fills and may crop; contain fits 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

6 Walkthroughs

1

Make a stylesheet work and inspect it

10 steps
Connect a page to CSS, trace a small rule, and diagnose a change that does not appear.
  1. 1
    IntroductionFrom 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.

  2. 2
    ExampleConnect an external file

    Suppose index.html sits beside a folder named css, which contains styles.css. Add this inside the HTML head:

    <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.

  3. 3
    ExplanationWrite and read one rule

    Put this in the linked stylesheet:

    p {
      color: navy;
      font-size: 18px;
    }
    

    p selects 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.

  4. 4
    ChallengeRepair 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.

  5. 5
    Key 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.

  6. 6
    ConnectionKeep 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.

  7. 7
    TipInspect 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.

  8. 8
    ChallengeExplain 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.

  9. 9
    ChallengeFollow the failed change

    A page still shows default paragraph styling. The Network panel reports a failed request for styles.css, while the actual file is css/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.

  10. 10
    RecapA 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.

2

Read selectors against the HTML tree

12 steps
Match reusable classes, states, parts and structural relationships without selecting extra elements.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDescribe the intended match
  2. 2
    ExampleReuse one class across elements
  3. 3
    ChallengeA space changes the target
  4. 4
    TipShare rules without requiring nesting
  5. 5
    ExplanationMatch attributes and current states
  6. 6
    ExampleCount siblings, not paragraphs alone
  7. 7
    ChallengeChoose a marker without replacing text
  8. 8
    ExplanationFind direct children in a nested list
  9. 9
    ExampleTrace the two sibling relationships
  10. 10
    ChallengeKeep the same parent in view
  11. 11
    ChallengeCombine location with state
  12. 12
    RecapRead the selector as a matching test
3

Trace a conflict from priority to inheritance

13 steps
Find winning declarations, calculate specificity and distinguish local values from inherited ones.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionOne element can have several winners
  2. 2
    ExplanationFilter before comparing
  3. 3
    ExampleResolve an inline color
  4. 4
    Key InsightUse layers before stronger selectors
  5. 5
    ChallengeName the deciding stage
  6. 6
    ExampleCount selector parts by column
  7. 7
    ExplanationHandle functional selectors
  8. 8
    ChallengeCompare without adding columns
  9. 9
    ConnectionLet text inherit and boxes stay separate
  10. 10
    ExplanationChoose the reset you intend
  11. 11
    ChallengeSeparate a child from its parent’s selector
  12. 12
    ChallengeFollow the complete decision
  13. 13
    RecapGive each decision its own job
4

Choose a color and calculate a relative size

10 steps
Interpret color channels and transparency, then trace font, container and viewport references.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionRead the reference behind the value
  2. 2
    ExampleDecode three color channels
  3. 3
    Key InsightKeep solid text over a translucent fill
  4. 4
    ChallengeCheck the right threshold
  5. 5
    ExampleCompute text size before its spacing
  6. 6
    ConnectionAvoid repeated growth in nested text
  7. 7
    ExplanationGive percentages the right reference
  8. 8
    ChallengeApply two different references
  9. 9
    ChallengeConnect font size to contrast
  10. 10
    RecapChoose what the value should follow
5

Measure a card and explain its gaps

11 steps
Calculate both box models, then trace inline behavior, centering and collapsed margins.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionStart at the content and work outward
  2. 2
    ExplanationName the four layers
  3. 3
    ExampleCalculate a content-box card
  4. 4
    ExampleSwitch what the width includes
  5. 5
    ChallengeFix a full-width overflow
  6. 6
    ConnectionMake a link accept dimensions
  7. 7
    ExampleSplit the remaining horizontal space
  8. 8
    Key InsightCombine vertical margins
  9. 9
    ChallengePredict a mixed-sign gap
  10. 10
    ChallengeRecalculate the centered card
  11. 11
    RecapMeasure the layer that causes the problem
6

Build readable text and a finished card

15 steps
Set a dependable font, keep links usable, and add backgrounds and edges without unexpected resets or size changes.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive each visual choice a purpose
  2. 2
    ExplanationChoose a dependable font stack
  3. 3
    ExampleLoad a face and preserve visible text
  4. 4
    ChallengeCatch a font shorthand reset
  5. 5
    ExampleKeep line spacing proportional
  6. 6
    TipKeep menus and links understandable
  7. 7
    ChallengeSeparate the block from its contents
  8. 8
    ExampleFollow a background path
  9. 9
    ExampleScale a square photo into a wide box
  10. 10
    Key InsightLayer a tint above a photo
  11. 11
    ChallengeProtect the complete photograph
  12. 12
    ExplanationDraw an edge without moving its neighbors
  13. 13
    ChallengeRound the box, keep the measurement
  14. 14
    ChallengeFinish a stable interactive card
  15. 15
    RecapConnect decoration to the underlying rules

CSS practice questions

50 Practice Questions in 5 sets

Set 1: Read rules and predict simple results10 Practice Questions

Question 1 of 10

A rule contains color: 18px; padding: 12px;. What happens to these declarations?
  1. Both declarations are ignored.
  2. Color applies; padding is ignored.
  3. Color is ignored; padding applies.
  4. Both declarations apply normally.
Show answerHide answer
Answer: C
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

A page has no author CSS, yet a list is indented and its items have bullets. Where do these styles come from?
  1. The browser’s user-agent stylesheet.
  2. The list text’s inherited margins.
  3. The HTML file’s inline declarations.
  4. The editor’s automatic stylesheet.
Show answerHide answer
Answer: A
The browser supplies default CSS for HTML elements, including list markers and indentation. No author stylesheet is needed for those defaults to appear. Margins are not normally inherited, and the list’s visible markers do not show that the HTML file contains inline style declarations.

Question 3 of 10

An element has class="panel featured". What selector requires both class words on that same element?
  1. .panel .featured
  2. .panel, .featured
  3. panel.featured
  4. .panel.featured
Show answerHide answer
Answer: D
Joining the two class selectors without a space makes one element satisfy both conditions. A space would select a featured descendant inside a panel, which is a different relationship. A comma would allow either class independently, so it would also reach elements that have only one of the required classes.

Question 4 of 10

An article contains an h2, then two p elements. What does article p:first-child select?
  1. Only the first paragraph.
  2. Neither paragraph.
  3. Only the second paragraph.
  4. Both paragraphs.
Show answerHide answer
Answer: B
: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

Two normal, unlayered author rules are .badge { color: teal; } followed by .badge { color: maroon; }. What color wins?
  1. Teal.
  2. Maroon.
  3. The parent’s color.
  4. The browser’s default.
Show answerHide answer
Answer: B
Both declarations have the same origin, importance, layer status and selector specificity. The later declaration therefore wins, giving maroon. Choosing teal would treat the first declaration as permanent, but source order resolves this tie in favor of the last applicable declaration.

Question 6 of 10

What is the ID-CLASS-TYPE specificity of .panel > a:hover?
  1. 0-1-2
  2. 0-2-2
  3. 1-1-1
  4. 0-2-1
Show answerHide answer
Answer: D
The class and the hover pseudo-class each add one in the CLASS column, and 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

What six-digit hex color is equivalent to #4bd?
  1. #44bbdd
  2. #40b0d0
  3. #444bdd
  4. #4b4bdd
Show answerHide answer
Answer: A
Three-digit hex expands by repeating each digit within its channel pair: 4 becomes 44, b becomes bb and d becomes dd. The result is #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

A content-box element has width: 240px; padding: 12px; border: 3px solid; margin: 8px;. What is its border-box width?
  1. 240px.
  2. 255px.
  3. 270px.
  4. 286px.
Show answerHide answer
Answer: C
The content width is 240px, and both sides add 24px of padding plus 6px of border, giving 270px. The 8px side margins lie outside the border box. Including them would produce 286px of horizontal space, which answers a different measurement from the width requested.

Question 9 of 10

What font stack provides named choices and a working generic fallback?
  1. "Noto Sans", Arial, "sans-serif"
  2. "Noto Sans Arial", sans-serif
  3. "Noto Sans", "Arial sans-serif"
  4. "Noto Sans", Arial, sans-serif
Show answerHide answer
Answer: D
The family names are separate comma-delimited choices, and the unquoted generic 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

A 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?
  1. 30px text with 42px lines.
  2. 30px text with 28px lines.
  3. 20px text with 28px lines.
  4. 30px text with 45px lines.
Show answerHide answer
Answer: A
The heading’s font size is 1.5 times its parent’s 20px, so it becomes 30px. It inherits the unitless multiplier 1.4 and applies it to its own size, giving 42px lines. A 28px line height would come from inheriting a fixed computed length, not the unitless number used here.
Set 2: Apply selectors, spacing and decoration10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

The HTML file is /site/pages/team.html; the stylesheet is /site/css/theme.css. What relative href reaches the stylesheet?
  1. css/theme.css
  2. ../css/theme.css
  3. ../pages/theme.css
  4. ../../css/theme.css
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A section contains an h3, a p, an aside, then another p. What does h3 ~ p select within that section?
  1. Only the next paragraph.
  2. Only the final paragraph.
  3. The heading and both paragraphs.
  4. Both paragraph siblings.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A parent matches #article { color: olive; }, and its paragraph child matches p { color: purple; }. What color does the paragraph use?
  1. Purple from its own rule.
  2. Olive from the parent’s ID.
  3. Olive until a class is added.
  4. The browser default color.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A paragraph has style="color: coral;" and matches .notice { color: indigo !important; } in author CSS. What color is used?
  1. Coral.
  2. The parent’s color.
  3. Indigo.
  4. The browser’s default.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A parent’s font size is 18px. Its child has font-size: 1.5em; padding: 0.5em;. How much padding is set on each side?
  1. 9px.
  2. 27px.
  3. 13.5px.
  4. 36px.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A link remains an ordinary inline box, and width: 180px has no sizing effect. What display value keeps it inline-level while allowing that width?
  1. inline-block
  2. inline
  3. none
  4. block
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A border-box card has width: 260px; padding: 18px; border: 2px solid;. How wide is its content area?
  1. 260px.
  2. 224px.
  3. 300px.
  4. 220px.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A rule uses background-color: linear-gradient(white, navy);. Why is the gradient not shown?
  1. A gradient needs border-style.
  2. A gradient is an image value.
  3. A gradient needs a repeat value.
  4. Named colors are invalid stops.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A box has border-width: 4px; border-color: teal; and no other border declarations. Why is no border visible?
  1. The initial border width is zero.
  2. The initial border style is none.
  3. The border color needs an alpha value.
  4. The width needs border-box sizing.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Normal author CSS declares @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?
  1. Teal.
  2. Maroon.
  3. The inherited color.
  4. Navy.
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

A link has href="manual.PDF". What selector matches a PDF ending regardless of letter case?
  1. a[href^=".pdf" i]
  2. a[href=".pdf" i]
  3. a[href~=".pdf" i]
  4. a[href$=".pdf" i]
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A declaration works after you edit it in developer tools, but the change disappears after reload. What must you do to keep it?
  1. Save the working declaration in the stylesheet.
  2. Save a screenshot of the Styles panel.
  3. Reload again with the same element selected.
  4. Move the element to a different HTML parent.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A rule .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?
  1. .alert.urgent
  2. .alert, .urgent
  3. .alert .urgent
  4. p.alert.urgent
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A 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?
  1. Link B only.
  2. Link A only.
  3. Both links A and B.
  4. Neither link A nor B.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Two normal author declarations in the same layer use #menu a and .menu a.selected. Both match one link. Which selector has greater specificity?
  1. #menu a
  2. .menu a.selected
  3. They have equal specificity.
  4. The nearer ancestor decides.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Author CSS sets div { display: initial; }. What display value does the div get from that declaration?
  1. block
  2. inline-block
  3. none
  4. inline
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A caption uses 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?
  1. Only the background remains translucent.
  2. The text also becomes partly transparent.
  3. The text becomes solid black as well.
  4. The photo becomes part of the caption.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A containing block is 420px wide and 300px tall. What does padding-top: 10% resolve to on its child?
  1. 30px.
  2. 10px.
  3. 42px.
  4. 72px.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

In normal block flow, two adjoining vertical margins collapse: the first is 26px and the second is −9px. What gap results?
  1. 26px.
  2. 35px.
  3. 17px.
  4. −9px.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A square photo is used once, with no repetition, behind a 900px by 300px banner. What happens with background-size: contain; background-position: center;?
  1. A 300px square image leaves 300px gaps at each side.
  2. A 900px square image loses 300px at top and bottom.
  3. A 900px by 300px image fills the banner by stretching.
  4. A 300px square image leaves all 600px at the right.
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

What CSS comment can safely label a group of rules?
  1. // Article styles
  2. <!-- Article styles -->
  3. # Article styles
  4. /* Article styles */
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A rule h2, p..lead, blockquote { color: teal; } changes none of these elements. What explains the result?
  1. A comma requires all selectors to match one element.
  2. An invalid selector breaks the ordinary selector list.
  3. The blockquote selector cancels the heading selector.
  4. A list cannot mix class selectors and type selectors.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A 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?
  1. A; B and C.
  2. B; B and C.
  3. None; B and C.
  4. None; A, B and C.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Author CSS declares @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?
  1. Teal.
  2. Purple.
  3. Navy.
  4. The parent’s color.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A normal-size text color on white measures 4.2:1 contrast. What is its WCAG AA contrast result?
  1. It passes the normal-text minimum.
  2. It fails because all text needs 7:1.
  3. It passes only because white is used.
  4. It fails the normal-text minimum.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A content-box child has width: 100%; padding: 0 15px; in a 480px-wide content area, with no borders or margins. How wide is its border box?
  1. 480px.
  2. 510px.
  3. 495px.
  4. 450px.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A card’s border box is 360px wide. Its rule is 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?
  1. 360px declared; 308px content.
  2. 320px declared; 268px content.
  3. 360px declared; 312px content.
  4. 372px declared; 320px content.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An element first gets font-weight: 700; font-style: italic;, then font: 1.25rem/1.4 Arial, sans-serif;. What weight and style apply after the shorthand?
  1. Bold weight and italic style.
  2. Normal weight and italic style.
  3. Normal weight and normal style.
  4. Bold weight and normal style.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A navigation list has list-style: none; but its items are still indented. What additional rule removes the default indentation?
  1. text-indent: 0;
  2. list-style-position: inside;
  3. text-align: start;
  4. padding: 0;
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An inline-block link uses content-box sizing with a 1px border. Hover must show a stronger cue while preserving its content width and all box dimensions. What change meets that requirement?
  1. Raise the border width to 3px.
  2. Add a 3px outline on hover.
  3. Switch to border-box sizing.
  4. Add 2px padding on every side.
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

A stylesheet request succeeds. Its rule appears for an inspected span, and width: 160px is valid and not crossed out, but the span is still only as wide as its text. What explains this?
  1. The request used the wrong stylesheet.
  2. The span inherits a parent’s width.
  3. The span is an ordinary inline box.
  4. The span’s margin hides its width.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A list has exactly eight li children and no other element children. Which child positions match li:nth-child(3n+2)?
  1. 2, 5 and 8.
  2. 3 and 6.
  3. 1, 4 and 7.
  4. 2, 4, 6 and 8.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

All declarations are normal, unlayered author rules. A link inside <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?
  1. Teal.
  2. Navy.
  3. The inherited color.
  4. Purple.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A container has 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?
  1. Maroon text and a beige background.
  2. Maroon text and a transparent background.
  3. Initial text color and a transparent background.
  4. Initial text color and a beige background.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

The root font is 20px and a container is 700px wide. Its border-box child has width: calc(100% - 4rem); padding: 1em; border: 2px solid; font-size: 1.5rem;. What is the child’s content width?
  1. 620px.
  2. 556px.
  3. 576px.
  4. 616px.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A 500px-wide block has no padding or border. Its child has no padding or border and is an ordinary block with width: 320px; margin: 0 auto; text-align: center;. What horizontal margins and text alignment result?
  1. 180px on each side; centered text.
  2. 90px on each side; start-aligned text.
  3. Zero side margins; centered text.
  4. 90px on each side; centered text.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A web font is declared with @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?
  1. "Lumen Sans"
  2. "lumen-regular"
  3. "lumen-regular.woff2"
  4. "fonts/lumen-regular.woff2"
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Equal-specificity link rules set 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?
  1. Put the visited rule after the hover rule.
  2. Set purple on the link’s parent instead.
  3. Put the hover rule after the visited rule.
  4. Replace :hover with :active in the first rule.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A page at /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?
  1. Change only the URL to ../images/banner.jpg, keeping the existing order.
  2. Change only the shorthand to background-color: navy, keeping the existing URL.
  3. Write background: navy; before background-image: url("images/banner.jpg");.
  4. Write background: navy; before background-image: url("../images/banner.jpg");.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A rectangular box measures 160px by 80px and has border-radius: 50%. What rounded shape does its background make?
  1. A circle.
  2. An ellipse.
  3. A rounded square.
  4. A pill with straight side edges.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

84 Key Terms, each with its definition

A

Alpha
Alpha is the opacity component of a color value, running from fully transparent at zero to fully opaque at one or 100%.
A background with half alpha can reveal a photo behind it while the element's text remains fully solid.
Attribute selector
An attribute selector matches an element by an attribute's presence or by a condition on its value, using square-bracket syntax.
The selector a[href$=".pdf" i] can style document links even when the file ending is uppercase.
Auto margin
An automatic horizontal margin absorbs leftover space beside a block, allowing equal auto side margins to center a narrower box.
A block that already fills its container cannot visibly move when both side margins are set to auto.

B

Background image
A background image is a decorative image drawn behind a box's content and above its background color, with controllable sizing and repetition.
A CSS photo can fail to load while the box keeps its fallback color and the text stays in the document.
Background layer
A background layer is one image in a comma-separated background list, with the first listed image drawn above the later images.
A color below all the image layers can remain visible through transparent parts and uncovered gaps.
Background position
Background position places an image within its background area using keywords, lengths or percentages, with horizontal position first.
A centered cover image shares necessary cropping around its middle instead of keeping only the top-left corner.
Background size
Background size controls the rendered dimensions of a background image, with cover and contain preserving the image's proportions.
Cover may crop the top and bottom of a square photo in a wide box; contain may leave gaps beside it.
Block box
A block box normally starts on a new line, accepts dimensions and fills the available width of its container when its width is auto.
A paragraph can use a maximum width and automatic side margins while keeping left-aligned text inside.
Border
A border is the styled edge around the padding area of a box, with a width, style and color that participate in box sizing.
Two 2px side borders add 4px to a card's content-box width, even when a soft shadow is also drawn around that card.
Border radius
A border radius rounds a box's corners without adding to its dimensions, with values that can vary between the four corners.
A 50% radius makes a square box circular, while the same value on a rectangle produces an ellipse.
Box shadow
A box shadow draws an outer or inner shadow using offsets, optional blur and spread, and color, without adding box-model space.
A card can gain a soft shadow and keep the same computed border-box width and position among its neighbors.
Box sizing
Box sizing determines whether a declared width or height measures the content area alone or also includes padding and border.
Switching a padded full-width card to border-box can make its outer width fit its container again.

C

Calc function
The calc() function combines compatible CSS values in an expression, allowing a length to mix relative and absolute amounts.
The value calc(100% - 40px) leaves a fixed amount out of a container-relative width, with spaces around minus.
Cascade
The cascade is the ordered process that chooses a winning declaration for each property on each element when CSS rules compete.
A paragraph can take its color from a class rule and its font size from a separate type-selector rule.
Cascade layer
A cascade layer is a named group of rules with an explicit priority relative to other layers, compared before selector specificity.
A normal component-layer class can beat an ID-based base-layer rule when the component layer comes later.
Ch unit
A ch is a font-relative length based on the advance width of the zero character, often used to limit the width of text columns.
A paragraph at max-width: 65ch follows the font size without promising exactly 65 letters per line.
Child
A child is an element directly nested inside a parent element, with no other element between the two in the HTML tree.
The selector .menu > li leaves out items whose parent is a separate nested list inside the menu.
Class selector
A class selector matches elements whose space-separated class attribute contains its named word, making the style reusable.
The selector .notice matches both a plain notice and an element with class="card notice".
Compound selector
A compound selector combines matching conditions without a combinator, requiring one element to satisfy all of those conditions.
The selector p.note reaches a paragraph with the note class, while p .note asks for a descendant.
Computed value
A computed value is a property value after the browser resolves its cascade and computation rules, before some layout-dependent resolution.
Developer tools can show that an em font size becomes pixels while a width percentage depends on layout.
Content area
The content area is the inner part of an element's box that holds its text, image or child content, inside the padding and border.
A content-box width of 300px leaves all 300px for content before padding is added to the outer dimensions.
Contrast ratio
A contrast ratio compares the relative luminance of foreground and background colors to measure their visible light-dark difference.
Text at 2.85:1 contrast fails both the normal-text and large-text WCAG AA minimum thresholds.
CSS
CSS is a language that describes the presentation of HTML elements, including their colors, fonts, spacing, borders and backgrounds.
A page can keep the same heading structure while a different stylesheet changes its colors and type.
CSS pixel
A CSS pixel is an absolute reference length used in page styling, which can correspond to multiple physical pixels on a dense display.
A 16px font can keep a similar intended size even when two screens have different device-pixel densities.
Current color
The currentColor keyword represents the element's own text color when another color-bearing property needs a matching value.
A border using currentColor changes with the text color when a hover rule updates only color.

D

Declaration
A declaration is a CSS property and value joined by a colon, assigning one part of an element's appearance within a rule.
In color: navy;, the declaration sets text color, and the semicolon separates it from the next setting.
Descendant
A descendant is an element nested anywhere inside another element, whether directly or through one or more intermediate elements.
The selector nav a reaches a navigation link even when a list and a list item sit between it and the nav.

E

Em unit
An 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.
After a child computes to 20px text, its 2em padding becomes 40px instead of following the parent again.

F

Focus-visible state
The focus-visible state matches a focused element when the browser determines that the reader needs a visible focus indicator.
A keyboard user can see an outline on the link selected by a:focus-visible before activating it.
Font stack
A font stack is an ordered list of font families, allowing the browser to fall back to another family when a preferred one is unavailable.
A stack ending in unquoted sans-serif still gives a suitable font on a device without the named fonts.
Font-face rule
An @font-face rule assigns a CSS family name and face characteristics to a font resource that can be used in a font stack.
The family declaration must match the rule's chosen name, not the filename appearing in its source URL.

G

Generated content
Generated content is text or a decorative box created by CSS pseudo-elements instead of being written as an HTML content node.
An asterisk added with ::after needs a content value; essential instructions stay in the HTML.
Generic font family
A generic font family names a broad font category for browser fallback, such as serif, sans-serif, monospace or system-ui.
Quoting sans-serif makes it a literal font name and removes its role as the stack's generic fallback.
Gradient
A gradient is a browser-generated image with colors that change along a line or outward from a center, used as an image value.
A translucent gradient listed before a photo can darken that photo without applying opacity to the overlaid text.

H

Hex color
A hex color writes red, green and blue channel values in base 16, with an optional extra pair for the color's transparency.
Expanding #3ac gives #33aacc because each digit becomes a repeated pair for its own channel.
HSL color
An HSL color describes hue as an angle together with percentage saturation and lightness, offering another notation for a color.
Keeping the hue fixed while increasing lightness can make a dark blue into a pale version of that blue.

I

ID selector
An ID selector matches an element's unique ID and contributes more specificity than class selectors in a competing rule.
A selector using #site-header can be harder to override later than one using a reusable header class.
ID-CLASS-TYPE triple
An ID-CLASS-TYPE triple records counts of IDs, class-like selectors and type-like selectors in three separately compared columns.
The selector a[href]:hover has the triple 0-2-1, with the attribute and hover counted as CLASS.
Important declaration
An important declaration is a CSS declaration marked with !important, giving it priority over normal declarations of the same origin.
An important author color can beat a normal inline color even when the stylesheet selector is just p.
Inherit keyword
The inherit keyword explicitly gives a property its parent's computed value, even when that property normally does not inherit.
Setting font: inherit on controls can replace their browser-assigned font with the surrounding text font.
Inheritance
Inheritance is the process by which an element receives its parent's value for an inherited property when no local value replaces it.
A body's font family can reach ordinary paragraphs without another font declaration on every paragraph.
Initial keyword
The initial keyword selects a property's starting value from the CSS specification, independent of the HTML element's default rule.
Applying display: initial to a div gives inline display even though the browser normally makes it block.
Inline box
An ordinary inline box flows within a line of text and takes its width from its content, ignoring explicit width and height.
A span does not become 200px wide just because a rule assigns width: 200px while it remains inline.
Inline-block box
An inline-block box joins a line of text while accepting explicit dimensions and reserving vertical space for its box spacing.
A navigation link can gain padded clickable space without forcing every link onto a separate line.

L

Line height
Line height sets the height used for a line of text; a unitless value acts as a multiplier of the element's own font size.
At 20px text, a unitless line height of 1.5 gives 30px lines and can scale appropriately for larger children.
Link state
A link state is a matching condition such as unvisited, visited, focused, hovered or active that can select a link for styling.
A visited link can also be hovered, so the order of equal-specificity color rules affects its appearance.
List marker
A list marker is the bullet, number or other indicator associated with a list item, styled through list properties or ::marker.
Changing a marker to a square does not remove the list container's separate default indentation.

M

Margin
A margin is transparent space outside a box's border, used to separate it from neighboring boxes and excluded from declared width.
A background cannot color the gap created by a margin, so colored inner spacing needs padding instead.
Margin collapsing
Margin collapsing combines certain adjoining vertical block margins into one margin, using the largest positive and most negative values.
Adjacent positive 18px and 30px collapsing margins create a 30px gap, while horizontal margins stay separate.

N

Next-sibling combinator
The next-sibling combinator, +, selects a matching element immediately after another element when both share the same parent.
The selector h2 + p reaches an opening paragraph but stops matching when an aside appears between them.

O

Outline
An outline is a line drawn outside a box's border without reserving extra layout space, often used to indicate keyboard focus.
A link can gain a 3px focus outline without pushing nearby text away as a larger content-box border would.
Outline offset
An outline offset sets the gap between an element's outline and its border, changing the drawn cue without changing box dimensions.
A 2px offset separates a focus outline from a link's border so the two lines remain visually distinct.
Overflow
Overflow is content extending beyond a box's allowed dimensions, controlled by values such as visible, hidden, scroll and auto.
A code block with overflow: auto can scroll its long line without making the whole page wider.

P

Padding
Padding is the space between a box's content and its border, carrying the box's background and contributing to its dimensions.
Increasing a card's padding creates colored breathing room around its text instead of a transparent outside gap.
Percentage
A CSS percentage expresses a proportion of a reference determined by the property, such as container width or parent font size.
A 10% top padding in a 500px-wide container uses that width and resolves to 50px, regardless of height.
Pseudo-class
A pseudo-class is a selector condition that matches an element's state or structural position, written with a single colon.
The :checked pseudo-class can select a checkbox whose current checked state is not represented by a class.
Pseudo-element
A pseudo-element selects a part of an element or creates a generated part for styling, conventionally written with two colons.
A rule for li::marker can color list bullets while leaving the list item text at its existing color.

R

Rem unit
A rem is a length relative to the root element's font size, providing a shared reference across nested elements in the page.
Several nested items at 1.25rem keep the same text size when they share an unchanged root size.
Reset
A reset is a set of CSS rules that removes selected browser defaults so a design can establish its own consistent starting styles.
A rule removing all padding also removes the list indentation, which the design may need to restore.
Revert keyword
The revert keyword rolls a property back past the current style origin, exposing an applicable value from a lower origin.
An author rule with display: revert can restore a div's normal browser-assigned block display.
Revert-layer keyword
The revert-layer keyword rolls a property's value back past the current cascade layer so a lower-priority source can supply it.
A component layer can release its color setting and let the matching color from an earlier base layer appear again.
RGB color
An RGB color specifies the amounts of red, green and blue light, commonly as channel numbers from 0 to 255 in rgb().
The value rgb(30 144 255) gives the same channel amounts as the six-digit hex value #1e90ff.

S

Selector list
A selector list is a comma-separated group of selectors that share a declaration block while matching elements independently.
The rule for h1, h2, h3 can give all three heading levels one font family without requiring nesting.
Shorthand property
A shorthand property sets several related CSS properties at once and resets the included longhands that its value does not specify.
Writing background: white; can remove a photo previously assigned through background-image.
Sibling
A sibling is an element sharing the same parent as another element; sibling combinators use their order in the HTML tree.
A paragraph inside an aside is not a sibling of a heading outside the aside, even if they look adjacent.
Source order
Source order is the sequence of declarations as CSS is encountered, resolving a conflict only after earlier cascade comparisons tie.
Two identical class selectors setting color in one layer leave the later declaration as the winner.
Specificity
Specificity is a selector's ID-CLASS-TYPE weight, used to compare competing declarations after their earlier cascade priorities tie.
An ID selector can beat many classes in the same priority group because the ID column is compared first.
Standards mode
Standards mode is the browser's document-rendering mode that follows modern web standards, selected by a valid HTML doctype.
Placing <!DOCTYPE html> first avoids the legacy behavior that can affect a page in quirks mode.
Structural pseudo-class
A structural pseudo-class selects elements according to their position among siblings, such as first child or every second child.
A paragraph following a heading is the first paragraph, but it does not match p:first-child.
Style origin
A style origin identifies whether CSS comes from the author, the reader or the browser, forming one stage of cascade priority.
A normal author rule can replace the browser's default heading size without matching its selector weight.
Styles panel
The Styles panel is a developer-tools view of the rules matching a selected element, including declarations that lose in the cascade.
A crossed-out color in the Styles panel helps explain why a paragraph displays another rule's value.
Stylesheet
A stylesheet is a collection of CSS rules that a browser applies to a document, often stored in a separate file shared by several pages.
An HTML link to css/styles.css lets a page load its styling from the file in the neighboring folder.
Subsequent-sibling combinator
The subsequent-sibling combinator, ~, selects matching later siblings of an element, allowing other siblings in between.
The selector h2 ~ p can reach two paragraphs separated by an aside when all share the heading's parent.

T

Text alignment
Text alignment positions a block's inline content within its line space, with choices such as start, end, center and justify.
Centering the text inside a full-width paragraph does not make the paragraph box narrower or move its edges.
Text decoration
Text decoration draws lines such as an underline or strike-through on text, with optional settings for style, color and thickness.
A link can keep an underline as a recognizable cue while a hover rule increases only the line's thickness.
Text transform
Text transform changes the displayed capitalization of text through CSS without rewriting the wording stored in the HTML.
An uppercase label can come from normally capitalized HTML, preserving the original wording in the document.
Type selector
A type selector matches elements by their HTML name, letting a CSS rule apply to every element of a selected kind.
The selector p can establish paragraph spacing across the page without assigning a class to each one.

U

Universal selector
The universal selector, *, matches every element but contributes zero specificity, making it useful in broad defaults and resets.
A rule for * can reset margins, while a class selector can later supply spacing with greater specificity.
Unset keyword
The unset keyword follows normal inheritance for an inherited property and uses the initial value for a non-inherited property.
Using unset on color can preserve a parent's text color, while using it on margin removes a local margin.
User-agent stylesheet
A user-agent stylesheet is the browser's built-in set of CSS rules that gives HTML elements their default appearance.
Large headings and indented lists appear on a plain HTML page before an author adds a stylesheet.

V

Variable font
A variable font stores a range of font variations, such as weights, in a single resource instead of needing one static file per face.
One variable-font file can supply several requested weights when its declared range covers them.
Viewport unit
A viewport unit measures a proportion of the browser's viewport, with vw using width and vh using height as the reference.
A value of 10vh is 80px when the viewport height is 800 CSS pixels, even inside a shorter container.

W

Web font
A web font is a font resource downloaded for use on a page, allowing a design to offer a face not installed on the reader's device.
A page can show a fallback first and then display its chosen web font when the WOFF2 file finishes loading.

Z

Zero-specificity selector
A zero-specificity selector contributes no weight to a selector comparison; :where() also removes the weight of its arguments.
The selector :where(#main) p remains easy to override because only the paragraph contributes a type point.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started