LearnContact
Lesson 212 min read

How CSS Works

Learn how CSS connects with HTML, how browsers read and apply CSS rules, the three ways to add CSS, and how the cascade determines the final styles.

Introduction

In the previous lesson, you learned that HTML creates the structure of a webpage while CSS controls its visual presentation.

But how does the browser know which HTML element should receive which style?

How does a CSS rule written in one file change the appearance of an element written in another file?

To understand CSS properly, you need to understand the process that connects HTML elements with CSS rules.

CSS works by selecting elements, applying declarations, resolving conflicts between competing rules, calculating final values, and using those values during browser rendering.

Browser Loads HTML
Finds CSS
Parses CSS Rules
Matches Selectors
Resolves Conflicts
Calculates Final Styles
Renders Webpage
CSS Does Not Work Independently

CSS normally works by targeting elements in a document and providing presentation rules for those elements.

How Does CSS Work?

CSS works through rules that tell the browser which elements to select and what styles to apply to them.

A basic CSS rule contains a selector and one or more declarations.

Basic CSS Rule
h1 {
    color: blue;
    font-size: 40px;
}

In this example, h1 is the selector. It tells the browser which HTML elements should receive the styles.

The declarations inside the curly braces tell the browser how the selected elements should appear.

PartExamplePurpose
Selectorh1Selects matching HTML elements
PropertycolorIdentifies what should be changed
ValueblueDefines the new setting
Declarationcolor: blue;Combines a property and value
Declaration Block{ ... }Contains one or more declarations
Matching HTML
<h1>
    Welcome to CSS
</h1>
Find h1 Elements
Read Declarations
Apply color: blue
Apply font-size: 40px
Display Styled Heading
Selector → Property → Value

CSS selects an element, identifies the visual property to change, and provides the value that should be used.

Real-World Analogy

Imagine a school teacher giving instructions to groups of students.

The teacher first identifies who should follow the instruction and then gives the instruction itself.

For example, the teacher may say, "All students in Class A should wear blue shirts."

In CSS, the selector is similar to identifying Class A, while the declaration is similar to the instruction to wear blue shirts.

School InstructionCSS
StudentsHTML elements
Class ASelector
Shirt colorProperty
BlueValue
Wear blue shirtsDeclaration
Teacher instructionsStylesheet
Instruction Analogy
Teacher Instruction

"All students in Class A should wear blue shirts."

Class A
   │
   ▼
Who should follow the rule?
   │
   ▼
Selector

Blue Shirts
   │
   ▼
What should change?
   │
   ▼
Declaration
Equivalent CSS Idea
.class-a {
    shirt-color: blue;
}
Target First, Style Second

Every CSS rule needs a way to identify what should be styled and declarations that describe how it should appear.

HTML and CSS Connection

HTML and CSS are connected through selectors.

A selector searches the document for elements that match a particular pattern.

HTML
<h1>
    Main Heading
</h1>

<p>
    First paragraph.
</p>

<p>
    Second paragraph.
</p>
CSS
h1 {
    color: purple;
}

p {
    color: gray;
}

The browser matches the h1 selector with the <h1> element and the p selector with both <p> elements.

Read HTML Elements
Read CSS Selectors
Compare Selectors with Elements
Find Matches
Apply Declarations
CSS SelectorMatched HTML
h1All <h1> elements
pAll <p> elements
buttonAll <button> elements
imgAll <img> elements
One Rule Can Match Many Elements

A single CSS selector can apply the same styles to multiple matching HTML elements.

Three Ways to Add CSS

CSS can be added to an HTML document in three main ways.

1️⃣ Inline CSS

CSS is written directly inside an HTML element using the style attribute.

2️⃣ Internal CSS

CSS is written inside a <style> element within the HTML document.

3️⃣ External CSS

CSS is written in a separate .css file and connected to the HTML document.

Choose Styling Method
Write CSS Rules
Connect Rules to HTML
Browser Parses Styles
Styles Apply to Elements
MethodLocation
Inline CSSInside the HTML element
Internal CSSInside a <style> element
External CSSInside a separate .css file
All Three Methods Use CSS

The main difference is where the CSS is written and how it is connected to the HTML document.

1. Inline CSS

Inline CSS is written directly inside an HTML element using the style attribute.

Inline CSS
<h1 style="color: blue;">
    Welcome to CSS
</h1>

The style attribute contains CSS declarations that apply only to that specific element.

Multiple Inline Declarations
<p style="color: gray; font-size: 18px;">
    Learn CSS step by step.
</p>
PartExample
HTML Element<p>
Attributestyle
Propertycolor
Valuegray
Declarationcolor: gray;

Useful For

  • Quick testing.
  • Very small one-time changes.
  • Styles generated dynamically in specific situations.

Problems

  • Difficult to reuse.
  • Mixes structure and presentation.
  • Creates repeated code.
  • Difficult to maintain at scale.
Avoid Using Inline CSS for Complete Websites

Inline CSS is valid, but large amounts of inline styling quickly become repetitive and difficult to maintain.

2. Internal CSS

Internal CSS is written inside a <style> element in the HTML document.

The <style> element is normally placed inside the <head> section.

Internal CSS
<!DOCTYPE html>
<html>

<head>

    <title>
        My Website
    </title>

    <style>

        h1 {
            color: blue;
        }

        p {
            color: gray;
        }

    </style>

</head>

<body>

    <h1>
        Welcome
    </h1>

    <p>
        Learn CSS step by step.
    </p>

</body>

</html>

The CSS rules inside the <style> element can target multiple elements on the same page.

Advantages

  • Styles multiple elements.
  • No separate CSS file required.
  • Useful for single-page examples.
  • Better reuse than inline CSS.

Limitations

  • Styles are limited to one HTML document.
  • Repeated across multiple pages.
  • Can make large HTML files harder to manage.
Good for Learning Examples

Internal CSS is useful when practicing a concept in one HTML file because the HTML and CSS can be viewed together.

3. External CSS

External CSS is written in a separate file with the .css extension.

The stylesheet is connected to the HTML document using the <link> element.

Project Structure
project/
│
├── index.html
│
└── style.css
index.html
<!DOCTYPE html>
<html>

<head>

    <title>
        My Website
    </title>

    <link
        rel="stylesheet"
        href="style.css"
    >

</head>

<body>

    <h1>
        Welcome
    </h1>

    <p>
        Learn CSS step by step.
    </p>

</body>

</html>
style.css
h1 {
    color: blue;
}

p {
    color: gray;
}

The rel="stylesheet" attribute tells the browser that the linked resource is a stylesheet.

The href attribute provides the location of the CSS file.

PartPurpose
<link>Connects an external resource
rel="stylesheet"Identifies the resource as a stylesheet
href="style.css"Provides the stylesheet location
Browser Loads HTML
Finds <link>
Requests CSS File
Downloads CSS
Parses Rules
Applies Styles

Advantages

  • Reusable across multiple pages.
  • Keeps HTML cleaner.
  • Easier maintenance.
  • Better organization.
  • Useful for real projects.

Considerations

  • File path must be correct.
  • Stylesheet must load successfully.
  • Additional files must be organized properly.
Preferred for Most Websites

External stylesheets are commonly used for real projects because they make CSS reusable and easier to maintain.

Comparing the Three Methods

FeatureInlineInternalExternal
LocationHTML element<style> elementSeparate .css file
Reusable on Same PageNoYesYes
Reusable Across PagesNoNoYes
HTML CleanlinessLowMediumHigh
MaintenanceDifficult at scaleGood for one pageBest for larger projects
Common UseSmall one-time styleSingle-page examplesWebsites and applications

Small Learning Example

  • Internal CSS can be convenient.
  • HTML and CSS remain visible together.
  • Easy to test quickly.

Real Website

  • External CSS is usually preferred.
  • Styles can be reused.
  • Maintenance becomes easier.
One Element
Consider Inline CSS
One Standalone Page
Consider Internal CSS
Multiple Pages or Real Project
Use External CSS
Method Depends on the Situation

There is no rule that only one method can ever be used, but external CSS is usually the most maintainable choice for reusable project styles.

How Browser Applies CSS

After the browser receives CSS, it parses the stylesheet and creates an internal representation of the rules.

The browser then compares selectors with elements in the document.

HTML
<h1>
    Welcome
</h1>

<p>
    First paragraph.
</p>

<p>
    Second paragraph.
</p>
CSS
h1 {
    color: purple;
}

p {
    color: gray;
}
Parse CSS
Read Selector
Search Document
Find Matching Elements
Collect Applicable Declarations
Resolve Conflicts
Calculate Final Values
SelectorMatchesResult
h1<h1>Heading becomes purple
pBoth <p> elementsBoth paragraphs become gray
CSS Matching is Continuous

The browser determines which rules apply to elements according to selector matching and the rules of the cascade.

Understanding the Cascade

The word cascading is one of the most important parts of CSS.

An element can receive style declarations from many different sources and many different rules.

When multiple declarations compete to set the same property, the browser must determine which declaration wins.

Competing Rules
p {
    color: blue;
}

p {
    color: red;
}

Both rules target the same elements and set the same property.

Because these declarations otherwise have equal priority, the later declaration wins.

Final Result
Paragraph Color → Red
Collect Matching Rules
Check Importance and Origin
Check Cascade Layers
Compare Specificity
Check Scoping Proximity When Relevant
Compare Source Order
Choose Winning Declaration
The Cascade is More Than Source Order

Source order matters only after higher-priority cascade factors have been resolved.

Understanding Inheritance

Inheritance allows some CSS property values to pass from a parent element to its descendants.

HTML
<div>

    <h2>
        CSS Course
    </h2>

    <p>
        Learn CSS step by step.
    </p>

</div>
CSS
div {
    color: blue;
}

The color property is inherited by default, so the text inside the heading and paragraph can also appear blue.

Parent Gets color: blue
Child Has No Own Color
Property is Inherited
Child Uses Blue

Often Inherited

  • color
  • font-family
  • font-size
  • line-height
  • text-align

Usually Not Inherited

  • margin
  • padding
  • border
  • width
  • height
Not Every Property Inherits

Inheritance behavior depends on the property. Do not assume that every parent style automatically passes to children.

Understanding Specificity

Specificity is used by the cascade to compare competing selectors when declarations have otherwise comparable priority.

HTML
<p class="message">
    Learn CSS
</p>
CSS
p {
    color: blue;
}

.message {
    color: red;
}

Both selectors match the paragraph, but the class selector is more specific than the element selector.

Final Result
Paragraph Color → Red
Selector TypeExampleGeneral Specificity
Element SelectorpLower
Class Selector.messageHigher than element
ID Selector#noticeHigher than class
Inline Stylestyle="..."Very high author-level specificity
Multiple Rules Match
Compare Cascade Priority
Compare Specificity
More Specific Selector Wins
Apply Declaration
Do Not Memorize Specificity as a Simple Ranking Only

Specificity is compared using selector components. It is one part of the complete cascade, not the only rule that determines the winner.

Source Order

When competing declarations have equal cascade priority and equal specificity, the declaration that appears later wins.

Source Order Example
h1 {
    color: blue;
}

h1 {
    color: green;
}

Both selectors have equal specificity.

The second rule appears later, so the heading becomes green.

Result
First Rule   → color: blue
Second Rule  → color: green

Winning Value → green
Later Wins Only When Other Factors Are Equal

A later rule does not automatically defeat every earlier rule. Cascade priority and specificity are considered first.

Browser Default Styles

Browsers provide built-in styles for many HTML elements.

These styles come from the browser user-agent stylesheet.

This is why headings appear large, links often appear blue and underlined, and lists display markers even when you write no custom CSS.

HTML ElementTypical Browser Default
<h1>Large bold text with margins
<p>Block element with margins
<a>Blue underlined text
<ul>Bulleted list
<ol>Numbered list
<strong>Bold text
HTML Without Custom CSS
<h1>
    Welcome
</h1>

<p>
    This page has no custom CSS.
</p>

<a href="#">
    Learn More
</a>

The browser still displays these elements with basic visual differences because default styles are already provided.

HTML Element Exists
No Author Style Found
Browser Default Applies
Element Remains Readable
CSS Starts on Top of Existing Defaults

Your custom CSS often overrides or builds upon styles already provided by the browser.

Browser Rendering Flow

The browser performs several steps before displaying a styled webpage.

Request HTML
Parse HTML
Build DOM
Discover CSS
Request Stylesheets
Parse CSS
Build CSSOM
Match Rules
Resolve Cascade
Create Render Tree
Calculate Layout
Paint Page
HTML and CSS Processing
HTML
  │
  ▼
DOM
  │
  │
  ├──────────────┐
  │              │
  │             CSS
  │              │
  │              ▼
  │           CSSOM
  │              │
  └──────┬───────┘
         │
         ▼
   Style Calculation
         │
         ▼
     Render Tree
         │
         ▼
       Layout
         │
         ▼
        Paint
         │
         ▼
   Styled Webpage
StagePurpose
HTML ParsingCreates the document structure
CSS ParsingProcesses stylesheet rules
Selector MatchingFinds elements affected by rules
Cascade ResolutionDetermines winning declarations
Style CalculationCalculates final property values
LayoutCalculates sizes and positions
PaintDraws visual content
The Browser Calculates Final Styles

The CSS you write is processed together with browser defaults, inheritance, and other applicable rules before the final visual values are used.

Real-World Applications

Understanding how CSS works is essential when building and debugging real websites.

Multi-Page Websites

One external stylesheet can provide consistent styles across many pages.

Component Libraries

Reusable CSS rules can style repeated interface components.

Design Systems

Shared rules create consistent colors, typography, spacing, and components.

Responsive Interfaces

CSS rules adapt layouts and presentation across different screen sizes.

Debugging

Cascade and specificity knowledge helps explain why styles do or do not apply.

Web Applications

Large applications organize many stylesheets and reusable style rules.

E-Commerce

Shared styles keep products, buttons, forms, and layouts consistent.

Learning Platforms

External stylesheets provide consistent lesson, navigation, and code interfaces.

Create HTML Structure
Connect Stylesheet
Write Reusable Rules
Browser Matches Elements
Cascade Resolves Conflicts
Display Consistent Interface

Advantages

Understanding how CSS works provides important advantages when creating and maintaining websites.

Better Understanding

You understand why styles apply instead of memorizing random solutions.

Easier Debugging

You can inspect selectors, inheritance, specificity, and source order.

Reusable Styles

External stylesheets can be shared across multiple pages.

Cleaner HTML

Presentation can remain separate from document structure.

Predictable Results

Cascade knowledge makes style conflicts easier to understand.

Easier Maintenance

Shared styles can be updated from a central location.

Better Architecture

Styles can be organized according to project needs.

Consistent Design

The same stylesheet can maintain a unified appearance across a website.

Without Understanding CSS Flow

  • Random overrides.
  • Repeated declarations.
  • Frequent !important usage.
  • Confusing style conflicts.
  • Difficult maintenance.

With Understanding CSS Flow

  • Predictable styling.
  • Better selectors.
  • Cleaner overrides.
  • Faster debugging.
  • Maintainable styles.

Common Beginner Mistakes

Forgetting to Link the CSS File

An external stylesheet cannot apply if the HTML document does not load it.

Using the Wrong File Path

The href value must correctly point to the stylesheet location.

Writing CSS Inside the Wrong Place

Internal CSS belongs inside a <style> element, while external CSS belongs in a .css file.

Adding HTML Tags to a CSS File

An external CSS file contains CSS rules and should not include <style> tags.

Using Inline CSS Everywhere

Large amounts of inline CSS create repetition and make styles difficult to maintain.

Expecting Internal CSS to Style Other Pages

Internal styles apply only to the HTML document that contains them.

Thinking the First Rule Always Wins

The cascade determines the winning declaration using multiple factors.

Thinking the Last Rule Always Wins

Later source order matters only when competing declarations are otherwise equal in cascade priority.

Ignoring Specificity

A more specific selector may override another matching selector.

Ignoring Inheritance

Some values may come from parent elements even when the child has no direct declaration.

Assuming Every Property Inherits

Properties such as margin, padding, and border do not normally inherit.

Fighting Browser Defaults

Unexpected spacing or appearance may come from the browser user-agent stylesheet.

Using !important as the First Solution

The real problem may be selector matching, specificity, source order, or stylesheet organization.

Not Using Developer Tools

Browser developer tools show matched rules, overridden declarations, computed values, and inherited styles.

Poor Debugging

  • Add random declarations.
  • Repeat selectors.
  • Add more specificity.
  • Use !important.
  • Hope the style works.

Better Debugging

  • Check stylesheet loading.
  • Check selector matching.
  • Inspect overridden rules.
  • Check inheritance.
  • Understand the cascade.

Best Practices

  • Use external stylesheets for reusable website styles.
  • Use internal CSS for small standalone examples when appropriate.
  • Use inline CSS only when there is a clear reason.
  • Keep HTML structure separate from presentation when practical.
  • Use correct stylesheet file paths.
  • Use the .css extension for external stylesheets.
  • Place the <link> element inside the document <head>.
  • Use rel="stylesheet" when linking a standard stylesheet.
  • Check the href value carefully.
  • Keep project folders organized.
  • Use predictable stylesheet names.
  • Avoid spaces and confusing characters in file names.
  • Verify that the browser successfully loads the CSS file.
  • Use browser developer tools to inspect network requests when a stylesheet does not load.
  • Check the browser console for related errors.
  • Understand selector matching.
  • Understand that one selector can match multiple elements.
  • Understand that one element can match multiple selectors.
  • Learn the cascade.
  • Learn inheritance.
  • Learn specificity.
  • Learn source order.
  • Do not depend on source order alone.
  • Do not assume the last declaration always wins.
  • Remember that cascade origin and importance can affect priority.
  • Understand the effect of !important before using it.
  • Avoid excessive !important declarations.
  • Use selectors that are only as specific as necessary.
  • Avoid unnecessarily complex selectors.
  • Avoid deeply nested selectors.
  • Prefer reusable classes for reusable interface patterns.
  • Do not rely only on element selectors for large component systems.
  • Keep selector behavior predictable.
  • Understand which properties commonly inherit.
  • Do not assume every property inherits.
  • Use inherited typography intentionally.
  • Override inherited values only when necessary.
  • Understand browser default styles.
  • Inspect user-agent styles when unexpected defaults appear.
  • Choose a consistent approach for normalizing or resetting defaults when a project requires it.
  • Do not remove useful browser behavior without a reason.
  • Keep CSS rules readable.
  • Use consistent indentation.
  • Write declarations clearly.
  • Use one declaration per line for readable blocks.
  • Include semicolons consistently.
  • Use meaningful comments when the reason behind a rule is not obvious.
  • Avoid comments that only repeat the code.
  • Group related rules logically.
  • Keep shared styles reusable.
  • Avoid copying the same declarations into many elements.
  • Move repeated styles into reusable rules.
  • Use external stylesheets when multiple pages share the same design.
  • Avoid duplicating identical internal styles across many HTML pages.
  • Load only the stylesheets required by the project.
  • Avoid unnecessary duplicate stylesheet imports.
  • Be aware that stylesheet order can affect the cascade.
  • Keep stylesheet loading order intentional.
  • Do not add override files without understanding why they are required.
  • Debug the original conflict instead of continuously adding new overrides.
  • Inspect matched rules when a declaration does not apply.
  • Inspect crossed-out declarations in developer tools.
  • Inspect computed values.
  • Check whether a value is inherited.
  • Check whether the selector actually matches the element.
  • Check whether another rule has greater specificity.
  • Check whether another declaration uses !important.
  • Check whether the stylesheet is loaded.
  • Check whether the CSS contains syntax errors.
  • Check whether the property value is valid.
  • Check whether the property applies in the current layout context.
  • Refresh the browser after changes.
  • Use hard refresh only when caching is actually causing a problem.
  • Avoid guessing during debugging.
  • Change one relevant thing at a time.
  • Use small examples to understand cascade behavior.
  • Practice with competing selectors.
  • Practice inheritance examples.
  • Practice source-order examples.
  • Learn to predict the winning declaration before checking the browser.
  • Keep real project styles maintainable.
  • Choose a CSS organization strategy appropriate for project size.
  • Do not over-engineer very small stylesheets.
  • Do not keep very large projects in one unorganized stylesheet.
  • Use shared styles for common design patterns.
  • Use component-specific styles for component behavior.
  • Keep global styles intentional.
  • Avoid broad selectors that accidentally affect unrelated content.
  • Test stylesheet changes across all affected pages.
  • Remember that changing a shared stylesheet can affect many pages.
  • Use version control for project changes.
  • Review CSS changes before deployment.
  • Minify production styles when supported by the build process.
  • Keep development source readable.
  • Use source maps when build tools transform CSS.
  • Understand generated CSS before debugging it.
  • Do not blame the browser before checking the cascade.
  • Use standards-based CSS.
  • Test important interfaces in multiple browsers.
  • Check browser support when using newer features.
  • Provide fallbacks when the project requires them.
  • Keep accessibility in mind when overriding browser defaults.
  • Preserve visible keyboard focus.
  • Preserve readable text.
  • Preserve sufficient contrast.
  • Avoid removing useful form controls without accessible replacements.
  • Remember that CSS affects presentation, not document meaning.
  • Keep meaningful content in HTML.
  • Use CSS for presentation.
  • Build a strong understanding of how the browser applies styles.
  • Master CSS flow before moving to complex layouts.
Inspect Before You Override

When a style does not work, first inspect the element and determine which rule is winning before adding another declaration.

Frequently Asked Questions

How does CSS work?

CSS works by matching selectors with document elements and applying declarations according to the cascade.

How does CSS connect to HTML?

CSS can connect to HTML through inline style attributes, internal <style> elements, or external stylesheets linked with <link>.

What are the three ways to add CSS?

The three main methods are inline CSS, internal CSS, and external CSS.

What is inline CSS?

Inline CSS is written directly inside an HTML element using the style attribute.

What is internal CSS?

Internal CSS is written inside a <style> element in the HTML document.

What is external CSS?

External CSS is written in a separate .css file and connected to HTML using a <link> element.

Which CSS method is best?

External CSS is usually preferred for reusable styles in real websites, while other methods remain useful in specific situations.

Where should the <link> element be placed?

A stylesheet <link> element is normally placed inside the <head> section of the HTML document.

What does rel="stylesheet" mean?

It tells the browser that the linked resource is a stylesheet.

What does href do in the <link> element?

The href attribute provides the location of the stylesheet file.

Can one CSS file style multiple HTML pages?

Yes. Multiple HTML pages can link to the same external stylesheet.

Can one HTML page use multiple CSS files?

Yes. A document can load multiple stylesheets.

What is the cascade?

The cascade is the process that determines which declarations win when multiple CSS rules compete.

What is inheritance?

Inheritance allows some property values to pass from parent elements to descendants.

Do all CSS properties inherit?

No. Some properties inherit by default while many others do not.

What is specificity?

Specificity is a selector-based comparison used by the cascade when resolving competing declarations.

Does the last CSS rule always win?

No. Later source order wins only when other relevant cascade factors are equal.

Why is my CSS file not working?

Common causes include an incorrect file path, missing <link> element, selector mismatch, syntax error, caching, or another declaration overriding the style.

Should external CSS contain <style> tags?

No. An external .css file should contain CSS rules directly.

Why does HTML have styles without my CSS?

Browsers provide built-in user-agent styles for many HTML elements.

What is a user-agent stylesheet?

It is the browser’s built-in stylesheet that provides default presentation for HTML elements.

Why does an h1 appear large without CSS?

The browser applies a default heading style through its user-agent stylesheet.

Why are some declarations crossed out in developer tools?

They may have been overridden by declarations that win through the cascade.

What should I check when CSS does not apply?

Check stylesheet loading, selector matching, syntax, inheritance, specificity, importance, and source order.

What happens after the browser reads CSS?

The browser parses the rules, matches selectors, resolves the cascade, calculates final styles, performs layout, and paints the page.

Key Takeaways

  • CSS works by matching selectors with document elements.
  • CSS declarations contain properties and values.
  • A selector identifies which elements should be styled.
  • A property identifies what should change.
  • A value defines the setting that should be used.
  • One CSS rule can style multiple elements.
  • One HTML element can match multiple CSS rules.
  • CSS can be added in three main ways.
  • Inline CSS is written inside the style attribute.
  • Internal CSS is written inside a <style> element.
  • External CSS is written in a separate .css file.
  • External stylesheets are connected using the <link> element.
  • The rel="stylesheet" value identifies a stylesheet.
  • The href attribute provides the stylesheet location.
  • External CSS can be reused across multiple pages.
  • Internal CSS applies to one HTML document.
  • Inline CSS applies directly to a specific element.
  • External CSS is commonly preferred for real projects.
  • The browser parses HTML and CSS separately.
  • HTML creates the DOM.
  • CSS contributes to the CSSOM.
  • The browser matches selectors with elements.
  • Multiple rules can compete for the same property.
  • The cascade determines the winning declaration.
  • The cascade is not based only on source order.
  • Specificity helps compare competing selectors.
  • A class selector is generally more specific than an element selector.
  • An ID selector is generally more specific than a class selector.
  • Source order matters when other relevant factors are equal.
  • Later declarations can win when competing rules have equal priority.
  • Some CSS properties inherit.
  • Inherited values can pass from parents to descendants.
  • Not every CSS property inherits.
  • Color and typography properties commonly inherit.
  • Margin and padding do not normally inherit.
  • Browsers provide default styles.
  • Browser defaults come from user-agent stylesheets.
  • Custom CSS can override browser default presentation.
  • Developer tools help inspect applied styles.
  • Crossed-out declarations have usually lost a cascade conflict.
  • Computed styles show final calculated values.
  • Correct file paths are required for external stylesheets.
  • External CSS files should not contain <style> tags.
  • Understanding the cascade makes CSS debugging easier.
  • Understanding inheritance prevents unnecessary repetition.
  • Understanding specificity prevents random overrides.
  • CSS should be organized for maintainability.
  • Inspect existing rules before adding overrides.
  • A strong understanding of how CSS works is essential before learning advanced CSS.

Summary

CSS works by using selectors to identify elements and declarations to describe how those elements should appear.

A CSS declaration combines a property with a value, while a CSS rule combines a selector with one or more declarations.

CSS can be added to HTML using inline styles, internal stylesheets, or external stylesheets.

Inline CSS is written directly inside an element, internal CSS is written inside a <style> element, and external CSS is stored in a separate .css file.

External stylesheets are commonly preferred for real projects because they can be reused across multiple pages and maintained from a central location.

When the browser processes CSS, it matches selectors with document elements and collects the declarations that apply.

If multiple declarations compete for the same property, the cascade determines which declaration wins.

Specificity, inheritance, and source order are important concepts for understanding why a particular style appears.

Browsers also provide default styles through user-agent stylesheets, which is why HTML elements have basic presentation even without custom CSS.

Understanding how stylesheets load, how selectors match, and how the cascade resolves conflicts makes CSS easier to write and debug.

In the next lesson, you will learn CSS syntax in detail, including selectors, declaration blocks, properties, values, comments, and the rules for writing valid CSS.