3.1: CSS Introduction & Syntax

Learn the fundamentals of CSS and how to apply styles to HTML elements using selectors, properties, and values. Understand the three ways to add CSS to your web pages and master the basic syntax for writing effective stylesheets.

1. What is CSS?

CSS (Cascading Style Sheets) is the language used to style and layout web pages.

The Three Pillars of Web Development

HTML (Structure)  →  The skeleton (content and structure)
CSS (Presentation) →  The skin (visual appearance and layout)
JavaScript (Behavior) →  The muscles (interactivity and dynamics)

What CSS controls:

  • šŸŽØ Colors and backgrounds
  • šŸ“ Layout and positioning
  • ✨ Typography (fonts, sizes, spacing)
  • šŸ“± Responsive design
  • šŸŽ¬ Animations and transitions
  • šŸ–¼ļø Visual effects

Why CSS Matters

Without CSS:

<h1>Welcome</h1>
<p>This is plain HTML</p>

Result: Black text on white background, default Times New Roman font, no spacing

With CSS:

h1 {
  color: #42b883;
  font-size: 48px;
  font-family: 'Arial', sans-serif;
  margin-bottom: 20px;
}

p {
  color: #333;
  line-height: 1.6;
  font-size: 18px;
}

Result: Beautiful, readable, professional-looking webpage


2. CSS Syntax

CSS follows a simple pattern: selector + declaration block

Basic Syntax Structure

selector {
  property: value;
  property: value;
}

Example:

h1 {
  color: blue;
  font-size: 32px;
  text-align: center;
}

Breakdown:

  • h1 = Selector (what to style)
  • { } = Declaration block (contains styling rules)
  • color: blue; = Declaration (property + value)
  • color = Property (what aspect to style)
  • blue = Value (how to style it)
  • ; = Semicolon (separates declarations)

Multiple Selectors

Target multiple elements with the same styles:

h1, h2, h3 {
  font-family: 'Georgia', serif;
  color: #2c3e50;
}

p, li, td {
  line-height: 1.6;
}

Case Sensitivity

CSS is case-insensitive for properties and values (except URLs and font names):

/* All valid */
COLOR: red;
color: RED;
Color: Red;

/* But be consistent - use lowercase */
color: red; /* āœ“ Recommended */

3. Three Ways to Apply CSS

Method 1: Inline CSS

Applied directly to HTML elements using the style attribute.

<h1 style="color: blue; font-size: 36px;">Hello World</h1>
<p style="color: gray;">This is a paragraph.</p>

Pros:

  • āœ… Highest specificity (overrides other styles)
  • āœ… Quick for testing

Cons:

  • āŒ Difficult to maintain
  • āŒ Mixes content with presentation
  • āŒ Cannot be reused
  • āŒ Not recommended for production

When to use: Testing, email templates, or dynamic styles from JavaScript

Method 2: Internal CSS

Defined within a <style> tag in the HTML document's <head>.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Internal CSS Example</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
      margin: 0;
      padding: 20px;
    }

    h1 {
      color: #333;
      border-bottom: 3px solid #42b883;
      padding-bottom: 10px;
    }

    p {
      color: #666;
      line-height: 1.8;
    }
  </style>
</head>
<body>
  <h1>Welcome</h1>
  <p>This page uses internal CSS.</p>
</body>
</html>

Pros:

  • āœ… Keeps CSS with the HTML
  • āœ… Good for single-page sites
  • āœ… Faster loading (no external request)

Cons:

  • āŒ Cannot be reused across pages
  • āŒ Makes HTML file larger
  • āŒ Harder to maintain multiple pages

When to use: Single-page applications, prototypes, or page-specific styles

Method 3: External CSS (Best Practice)

CSS is written in a separate .css file and linked to HTML.

styles.css:

/* Main stylesheet */
body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  line-height: 1.6;
  color: #333;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  color: #2c3e50;
  font-size: 2.5em;
  margin-bottom: 1em;
}

p {
  margin-bottom: 1em;
}

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>External CSS Example</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Welcome</h1>
  <p>This page uses external CSS.</p>
</body>
</html>

Pros:

  • āœ… Reusable across multiple pages
  • āœ… Maintainable - one file to update
  • āœ… Cacheable - faster subsequent loads
  • āœ… Separation of concerns - HTML for structure, CSS for style
  • āœ… Recommended for all projects

Cons:

  • āŒ Requires extra HTTP request (minimal impact)

Multiple Stylesheets:

<link rel="stylesheet" href="reset.css">
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="layout.css">
<link rel="stylesheet" href="components.css">

4. The Cascade

The "C" in CSS stands for Cascading - styles flow down and can be overridden.

How the Cascade Works

When multiple rules target the same element, CSS applies them in this order:

  1. Origin: Browser defaults → User styles → Author styles
  2. Specificity: More specific selectors win
  3. Source order: Last rule wins (if specificity is equal)

Example:

/* First rule */
p {
  color: blue;
}

/* Second rule - overwrites first */
p {
  color: red;
}

/* Result: paragraphs are red */

Cascade in Action

<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="theme.css">

<style>
  p { color: purple; }
</style>

<p style="color: orange;">Text here</p>

Applied order:

  1. base.css: p { color: blue; }
  2. theme.css: p { color: green; } ← Overrides base.css
  3. Internal style: p { color: purple; } ← Overrides theme.css
  4. Inline style: color: orange; ← Wins (highest specificity)

5. Specificity

Specificity determines which CSS rule applies when multiple rules target the same element.

Specificity Hierarchy

From lowest to highest specificity:

1. Element selectors        →  p, div, h1
2. Class selectors          →  .class-name
3. ID selectors             →  #id-name
4. Inline styles            →  style="..."
5. !important               →  color: red !important;

Calculating Specificity

Think of it as a four-digit number: 0,0,0,0

Position:  [inline, ID, class, element]

Examples:
p                    →  0,0,0,1  (1 element)
.intro               →  0,0,1,0  (1 class)
p.intro              →  0,0,1,1  (1 class + 1 element)
#header              →  0,1,0,0  (1 ID)
#header .nav         →  0,1,1,0  (1 ID + 1 class)
div#header .nav p    →  0,1,1,2  (1 ID + 1 class + 2 elements)

Specificity Examples

<p class="text" id="intro">Hello World</p>
/* Specificity: 0,0,0,1 */
p {
  color: blue;
}

/* Specificity: 0,0,1,0 - WINS over p */
.text {
  color: green;
}

/* Specificity: 0,1,0,0 - WINS over .text */
#intro {
  color: red;
}

/* Result: Text is red */

The !important Exception

!important overrides everything (even inline styles):

p {
  color: blue !important;
}

/* Even this won't work: */
p {
  color: red;
}

Warning: Avoid !important - it makes debugging difficult. Use it only for:

  • Overriding third-party CSS you can't modify
  • Utility classes that must always apply

6. Inheritance

Some CSS properties are inherited from parent elements to children.

Inherited Properties

Text-related properties inherit:

  • color
  • font-family
  • font-size
  • font-weight
  • line-height
  • text-align
  • letter-spacing
<div style="color: blue; font-family: Arial;">
  <p>This paragraph inherits blue color and Arial font</p>
  <span>This span also inherits</span>
</div>

Non-Inherited Properties

Box model and layout properties don't inherit:

  • margin
  • padding
  • border
  • width
  • height
  • background
div {
  border: 2px solid black;
  padding: 20px;
}

/* Child p does NOT inherit border or padding */
p {
  /* No border or padding unless explicitly set */
}

Forcing Inheritance

Use the inherit keyword:

.parent {
  border: 1px solid black;
}

.child {
  border: inherit; /* Now inherits parent's border */
}

Other Inheritance Keywords

.element {
  color: initial;     /* Browser default */
  margin: unset;      /* Removes all values */
  padding: inherit;   /* Inherit from parent */
}

7. CSS Comments

Comments help document your code and make it maintainable.

Comment Syntax

/* This is a single-line comment */

/*
 * This is a multi-line comment
 * spanning several lines
 */

/* Header Styles */
header {
  background: #333;
}

/* Navigation Menu */
nav {
  display: flex;
  /* justify-content: center; */ /* Temporarily disabled */
}

Best Practices for Comments

Section Headers:

/* ===========================
   GLOBAL STYLES
   =========================== */

body {
  margin: 0;
  padding: 0;
}

/* ===========================
   NAVIGATION
   =========================== */

nav {
  /* styles */
}

Explaining Complex Code:

.element {
  /* Fix for IE11 flexbox bug */
  flex-shrink: 0;

  /* Prevent text selection on double-click */
  user-select: none;
}

TODOs and Notes:

/* TODO: Update colors to match new brand guidelines */
/* NOTE: This is a temporary fix until redesign */
/* BUG: Safari doesn't support this property */

8. CSS Values and Units

Color Values

/* Named colors */
color: red;
color: blue;
color: transparent;

/* Hexadecimal */
color: #ff0000;      /* Red */
color: #f00;         /* Short hex */
color: #ff000080;    /* With alpha */

/* RGB/RGBA */
color: rgb(255, 0, 0);           /* Red */
color: rgba(255, 0, 0, 0.5);     /* 50% transparent red */

/* HSL/HSLA */
color: hsl(0, 100%, 50%);        /* Red */
color: hsla(0, 100%, 50%, 0.5);  /* 50% transparent red */

Length Units

Absolute:

width: 100px;    /* Pixels */
width: 2cm;      /* Centimeters */
width: 1in;      /* Inches */

Relative:

font-size: 1.5em;     /* 1.5 times parent font size */
font-size: 1.5rem;    /* 1.5 times root font size */
width: 50%;           /* 50% of parent width */
width: 50vw;          /* 50% of viewport width */
height: 100vh;        /* 100% of viewport height */

Other Common Values

/* Keywords */
display: none;
text-align: center;
font-weight: bold;

/* Numbers */
opacity: 0.5;
z-index: 100;
line-height: 1.6;

/* Multiple values */
margin: 10px 20px;              /* top/bottom left/right */
padding: 10px 20px 30px 40px;   /* top right bottom left */

9. Browser Developer Tools for CSS

Inspecting Elements

Chrome/Edge/Firefox:

  1. Right-click element → "Inspect"
  2. Or press F12 → Elements/Inspector tab

What you can do:

  • āœ… See all applied styles
  • āœ… See computed values
  • āœ… Edit styles in real-time
  • āœ… Toggle properties on/off
  • āœ… See specificity conflicts

DevTools Features

Styles Panel:

element.style { }           ← Inline styles
.class-name { }             ← Applied classes
element { }                 ← Element styles
Inherited from parent { }   ← Inherited properties

Computed Panel:

  • Shows final calculated values
  • Box model visualization
  • All properties alphabetically

Console Tricks:

// Get computed styles
getComputedStyle(document.querySelector('h1')).color

// Get all stylesheets
document.styleSheets

10. Practical Exercises

Exercise 3.1.1: Basic CSS Application

Create an HTML file and apply CSS using all three methods:

  1. Add inline style to make an <h1> blue
  2. Use internal CSS to make all paragraphs gray
  3. Create external stylesheet to add background color to body

Observe: Which style wins when multiple rules target the same element?

Exercise 3.1.2: Specificity Challenge

Given this HTML:

<p class="text" id="intro">Test</p>

Write CSS rules with different specificity and predict which color wins:

p { color: blue; }
.text { color: green; }
#intro { color: red; }
p.text { color: yellow; }

Test your prediction in the browser!

Exercise 3.1.3: Cascade Practice

Create two external stylesheets (first.css, second.css) with conflicting rules. Link both to an HTML page and observe the cascade order.

Exercise 3.1.4: Build a Styled Page

Create a simple blog post with:

  • External CSS file
  • Proper colors (hex, RGB, or HSL)
  • Different font sizes using em/rem
  • Commented CSS sections
  • At least 5 different properties

11. Knowledge Check

Question 1: What are the three ways to apply CSS to HTML?

Show answer Inline (style attribute), Internal (style tag in head), and External (separate .css file linked with link tag). External is the recommended method for production.

Question 2: Which has higher specificity: class selector or ID selector?

Show answer ID selector has higher specificity (0,1,0,0) than class selector (0,0,1,0).

Question 3: What is inheritance in CSS?

Show answer Inheritance is when child elements automatically receive certain CSS property values from their parent elements, particularly text-related properties like color and font-family.

Question 4: What happens when two CSS rules with equal specificity target the same element?

Show answer The last rule in source order wins (cascade).

Question 5: Which properties are inherited by default?

Show answer Text-related properties inherit: color, font-family, font-size, font-weight, line-height, text-align, etc. Box model properties (margin, padding, border) do NOT inherit.

Question 6: When should you use !important?

Show answer Rarely. Only when overriding third-party CSS you can't modify, or for critical utility classes. Overuse makes debugging difficult.

12. Common Mistakes to Avoid

āŒ Missing Semicolons

/* Wrong */
p {
  color: blue
  font-size: 16px
}

/* Correct */
p {
  color: blue;
  font-size: 16px;
}

āŒ Wrong Selector Syntax

/* Wrong */
p class="intro" {
  color: blue;
}

/* Correct */
p.intro {
  color: blue;
}

āŒ Overusing !important

/* Bad - hard to override */
.button {
  color: blue !important;
  background: red !important;
}

/* Good - use specificity instead */
.header .button {
  color: blue;
  background: red;
}

āŒ Mixing Methods Without Purpose

<!-- Bad - inconsistent -->
<style>
  p { color: blue; }
</style>
<p style="color: red;">Text</p>
<link rel="stylesheet" href="styles.css">

13. Key Takeaways

āœ… CSS controls presentation - colors, layout, typography, animations āœ… Three application methods - inline (avoid), internal (single pages), external (best practice) āœ… Cascade order - Origin → Specificity → Source order āœ… Specificity hierarchy - Element < Class < ID < Inline < !important āœ… Inheritance - Text properties inherit, box model doesn't āœ… Comments - Use /* comment */ to document code āœ… DevTools - Essential for debugging and learning CSS āœ… External CSS - Best for maintainability and reusability āœ… Avoid !important - Use specificity instead āœ… Proper syntax - selector { property: value; }


14. Further Resources

Official Documentation:

Learning Tools:

Reference:


Next Steps

Excellent work! You now understand CSS fundamentals, syntax, and how to apply styles to HTML documents.

In Lesson 3.2: Selectors & Specificity, you'll learn advanced CSS selectors, combinators, pseudo-classes, and pseudo-elements to target exactly the elements you need.