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:
- Origin: Browser defaults ā User styles ā Author styles
- Specificity: More specific selectors win
- 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:
- base.css:
p { color: blue; } - theme.css:
p { color: green; }ā Overrides base.css - Internal style:
p { color: purple; }ā Overrides theme.css - 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:
colorfont-familyfont-sizefont-weightline-heighttext-alignletter-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:
marginpaddingborderwidthheightbackground
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:
- Right-click element ā "Inspect"
- 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:
- Add inline style to make an
<h1>blue - Use internal CSS to make all paragraphs gray
- 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:
- CSS Specificity Calculator
- Can I Use - Browser support checker
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.