Chapter 3: CSS - Styling Web Pages
CSS (Cascading Style Sheets) is the language used to describe the visual presentation of HTML documents. Learn about selectors, properties, the box model, colors, typography, and responsive design.
- How CSS works and the cascade
- CSS selectors and specificity
- Colors, typography, and backgrounds
- The box model (margin, padding, border)
- CSS units (px, em, rem, %, vh, vw)
3.1 What is CSS?
CSS (Cascading Style Sheets) is the language used to describe the visual presentation of HTML documents. While HTML provides the structure and content of a web page, CSS controls how everything looks - colors, fonts, spacing, layout, animations, and responsive behavior across different devices.
Why CSS is Essential
- Separation of Concerns: CSS separates presentation from content, making code easier to maintain and update
- Consistency: One stylesheet can control the look of hundreds of pages across an entire website
- Responsive Design: CSS enables websites to adapt to different screen sizes (mobile, tablet, desktop)
- Performance: External CSS files are cached by browsers, improving page load times
- Accessibility: CSS allows visual customization without changing HTML structure
- Reusability: Write styles once, apply them to many elements
CSS Syntax
CSS consists of rules that target HTML elements and apply styles to them:
selector {
property: value;
property: value;
}
/* Example */
p {
color: blue;
font-size: 16px;
}
Selector: Targets which HTML elements to style
Property: The aspect you want to change (color, size, margin, etc.)
Value: What you want to set the property to
Declaration: A property-value pair (e.g., color: blue;)
Why "Cascading"?
The "Cascade" refers to how CSS rules are applied when multiple rules target the same element. The cascade determines which styles "win" based on three main factors:
1. Source Order - Rules cascade down from multiple sources in this priority:
- Browser default styles (lowest priority)
- External stylesheets
- Internal styles (<style> tag)
- Inline styles (highest priority)
2. Specificity - More specific selectors override less specific ones (covered in detail in section 3.2)
3. Importance - The !important declaration overrides normal
cascade rules:
p {
color: red !important; /* This will always win */
}
!important makes CSS hard to maintain.
Use it only as a last resort!
Three Ways to Add CSS
1. External Stylesheet (Recommended for production)
<!-- In your HTML <head> -->
<link rel="stylesheet" href="styles.css">
/* In styles.css file */
p { color: blue; }
Benefits: Reusable across pages, cacheable by browser, keeps HTML clean, easier to maintain
2. Internal Styles (Good for single-page styles)
<head>
<style>
p { color: blue; }
</style>
</head>
Use when: Styles are specific to one page only, or for quick prototyping
3. Inline Styles (Avoid when possible)
<p style="color: blue; font-size: 16px;">Text</p>
3.2 CSS Selectors
Selectors determine which HTML elements your styles apply to. They are the "targeting system" of CSS - mastering selectors is essential for efficient styling. CSS offers many types of selectors, from simple to very specific.
Basic Selectors
These are the foundation of CSS and are used most frequently:
/* Element/Type selector - selects ALL elements of that type */
p { color: blue; } /* Every <p> on the page */
h1 { font-size: 32px; } /* Every <h1> on the page */
div { margin: 10px; } /* Every <div> on the page */
/* Class selector (.) - reusable, can apply to MANY elements */
.highlight { background: yellow; }
.btn { padding: 10px 20px; }
.error-text { color: red; }
/* Used as: <p class="highlight">Text</p> */
/* Multiple classes: <div class="btn highlight"></div> */
/* ID selector (#) - UNIQUE, should only be used once per page */
#header { position: fixed; }
#main-content { max-width: 1200px; }
#footer { margin-top: auto; }
/* Used as: <div id="header"></div> */
/* Universal selector (*) - selects EVERYTHING */
* { box-sizing: border-box; } /* Common reset */
* { margin: 0; padding: 0; } /* Reset all spacing */
Grouping Selectors
Apply the same styles to multiple selectors at once using commas:
/* Without grouping - repetitive */
h1 { font-family: Arial; }
h2 { font-family: Arial; }
h3 { font-family: Arial; }
/* With grouping - clean and DRY */
h1, h2, h3 { font-family: Arial; }
/* Mix different selector types */
h1, .title, #main-heading { color: navy; }
Combinator Selectors
Combinators describe relationships between elements, allowing you to target elements based on their position in the HTML structure:
/* DESCENDANT selector (space) - any nested element, any depth */
nav a { text-decoration: none; } /* Any <a> inside <nav> */
article p { line-height: 1.6; } /* Any <p> inside <article> */
.container div span { ... } /* Multiple levels deep */
/* CHILD selector (>) - DIRECT children only, not grandchildren */
ul > li { margin: 5px; } /* Only direct <li> of <ul> */
.card > h2 { margin-top: 0; } /* Direct <h2> children of .card */
/* ADJACENT SIBLING (+) - immediately following element */
h2 + p { margin-top: 0; } /* First <p> right after <h2> */
label + input { margin-left: 10px; }
/* GENERAL SIBLING (~) - all following siblings */
h2 ~ p { color: gray; } /* All <p> elements after <h2> */
Visual Example:
<nav>
<ul>
<li><a>Home</a></li> <!-- nav a, ul > li, nav li -->
<li><a>About</a></li> <!-- li + li (adjacent sibling) -->
</ul>
</nav>
Attribute Selectors
Target elements based on their attributes or attribute values - very powerful for forms and links:
/* Has attribute (any value) */
[disabled] { opacity: 0.5; } /* Any element with disabled attr */
[required] { border-color: red; } /* Any required field */
/* Attribute equals exact value */
[type="submit"] { background: blue; }
[type="text"] { padding: 8px; }
input[type="email"] { ... } /* More specific */
/* Attribute STARTS WITH (^=) - great for external links */
[href^="https"] { color: green; } /* Secure links */
[href^="http"] { ... } /* External links */
[class^="btn-"] { ... } /* Classes starting with btn- */
/* Attribute ENDS WITH ($=) - great for file types */
[href$=".pdf"] { color: red; } /* PDF links */
[href$=".jpg"] { ... } /* JPG image links */
[src$=".png"] { ... } /* PNG images */
/* Attribute CONTAINS (*=) */
[class*="btn"] { cursor: pointer; } /* Any class containing "btn" */
[href*="google"] { ... } /* Links to Google */
Pseudo-classes and Pseudo-elements
Pseudo-classes select elements based on their state (like
hover) or
position (like first-child). They use a single colon (:).
/* INTERACTIVE STATES - respond to user actions */
a:link { color: blue; } /* Unvisited link */
a:visited { color: purple; } /* Already visited */
a:hover { color: red; } /* Mouse over */
a:active { color: orange; } /* Being clicked */
button:hover { background: #eee; } /* Mouse over button */
button:active { transform: scale(0.98); } /* Click effect */
input:focus { outline: 2px solid blue; } /* When selected */
/* FORM STATES - essential for form styling */
input:checked { ... } /* Checked checkbox/radio */
input:disabled { opacity: 0.5; } /* Disabled field */
input:enabled { ... } /* Enabled field */
input:required { border-color: red; } /* Required field */
input:valid { border-color: green; } /* Valid input */
input:invalid { border-color: red; } /* Invalid input */
input:placeholder-shown { ... } /* Placeholder visible */
/* POSITION-BASED - target by position in parent */
li:first-child { font-weight: bold; } /* First element */
li:last-child { border: none; } /* Last element */
li:only-child { ... } /* If it's the only child */
/* nth-child - very powerful! */
li:nth-child(3) { ... } /* 3rd item */
li:nth-child(odd) { background: #f0f0f0; } /* Odd rows */
li:nth-child(even) { background: #fff; } /* Even rows */
li:nth-child(3n) { ... } /* Every 3rd (3, 6, 9...) */
li:nth-child(3n+1) { ... } /* 1st of every 3 (1, 4, 7...) */
/* Count from the end */
li:nth-last-child(2) { ... } /* 2nd from last */
/* OTHER USEFUL PSEUDO-CLASSES */
p:empty { display: none; } /* Empty elements */
:not(.special) { ... } /* Everything EXCEPT .special */
p:not(:first-child) { ... } /* All p except first */
Pseudo-elements create "virtual" elements that don't exist in HTML,
allowing you to style specific parts of an element. They use double colons
(::).
/* INSERT CONTENT - content property required! */
p::before { content: "→ "; } /* Add before content */
p::after { content: " ←"; } /* Add after content */
/* Common use: Icons and decorations */
.required::after {
content: " *";
color: red;
}
.external-link::after {
content: " ↗";
}
/* STYLE PARTS OF TEXT */
p::first-letter { /* Drop cap effect */
font-size: 3em;
float: left;
}
p::first-line { font-weight: bold; } /* First line only */
/* USER SELECTION */
::selection { /* When user selects text */
background: yellow;
color: black;
}
/* FORM PLACEHOLDER */
input::placeholder { color: #999; }
Selector Specificity (Very Important!)
When multiple CSS rules target the same element, specificity determines which rule wins. This is one of the most important concepts to understand in CSS!
1. !important /* AVOID! Nuclear option, overrides everything */
2. Inline styles /* style="..." attribute (1,0,0,0) */
3. ID selectors /* #header (0,1,0,0) */
4. Class selectors /* .button (0,0,1,0) */
5. Element selectors /* p, div (0,0,0,1) */
6. Universal (*) /* (0,0,0,0) */
How to Calculate Specificity:
Count selectors in format: (Inline, IDs, Classes, Elements)
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 li /* (0,1,1,1) - 1 ID + 1 class + 1 element */
#header .nav li a.active /* (0,1,2,2) */
/* Example conflict: */
p { color: blue; } /* (0,0,0,1) */
.text { color: red; } /* (0,0,1,0) - WINS! */
#intro { color: green; } /* (0,1,0,0) - WINS over both! */
/* If specificity is equal, last rule wins: */
.text { color: red; }
.text { color: blue; } /* This wins (same specificity, later) */
- Keep specificity low - use classes instead of IDs
- Avoid
!important- it makes debugging very difficult - Be consistent with naming conventions (like BEM)
- If you can't override a style, check specificity first!
3.3 CSS Colors
Color is one of the most impactful aspects of web design. CSS provides multiple ways to specify colors, each with its own advantages. Understanding these formats is essential for working with design tools and creating accessible, visually appealing websites.
Color Properties
Colors can be applied to many properties:
color- Text colorbackground-color- Background fillborder-color- Border coloroutline-color- Outline colorbox-shadow- Shadow color
Named Colors
CSS has 147 predefined color names. Easy to read but limited options:
/* Basic named colors */
color: red;
color: blue;
color: green;
color: black;
color: white;
/* Extended named colors */
color: dodgerblue; /* Nice blue */
color: tomato; /* Red-orange */
color: coral; /* Pink-orange */
color: slategray; /* Gray-blue */
color: rebeccapurple; /* Purple (added as tribute) */
/* Special values */
color: transparent; /* Fully transparent */
color: currentColor; /* Inherits from color property */
color: inherit; /* Inherits from parent */
Hexadecimal Colors
The most common format in professional work. Uses base-16 (0-9, A-F) notation:
/* Full format: #RRGGBB (Red, Green, Blue) */
color: #ff0000; /* Pure Red (ff=255, 00=0, 00=0) */
color: #00ff00; /* Pure Green */
color: #0000ff; /* Pure Blue */
color: #000000; /* Black */
color: #ffffff; /* White */
color: #808080; /* Gray */
color: #3b82f6; /* Custom blue */
/* Shorthand: #RGB (when pairs repeat) */
color: #f00; /* Same as #ff0000 (Red) */
color: #0f0; /* Same as #00ff00 (Green) */
color: #fff; /* Same as #ffffff (White) */
color: #333; /* Same as #333333 (Dark gray) */
/* With alpha: #RRGGBBAA */
color: #ff000080; /* 50% transparent red (80 ≈ 50%) */
color: #0000ff40; /* 25% transparent blue */
Hex Values Explained: Each pair represents 0-255 in hexadecimal (00-FF). Think of it as mixing light: more = brighter.
RGB and RGBA Colors
RGB is more intuitive - specify Red, Green, Blue values from 0-255:
/* RGB - Red, Green, Blue (0-255 each) */
color: rgb(255, 0, 0); /* Red */
color: rgb(0, 255, 0); /* Green */
color: rgb(0, 0, 255); /* Blue */
color: rgb(0, 0, 0); /* Black */
color: rgb(255, 255, 255); /* White */
color: rgb(59, 130, 246); /* Custom blue */
/* RGBA - RGB with Alpha transparency (0-1) */
color: rgba(255, 0, 0, 1); /* Fully opaque red */
color: rgba(255, 0, 0, 0.5); /* 50% transparent red */
color: rgba(255, 0, 0, 0.25); /* 25% transparent red */
color: rgba(255, 0, 0, 0); /* Fully transparent */
/* Great for overlays and shadows */
background: rgba(0, 0, 0, 0.5); /* Semi-transparent black */
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
HSL and HSLA Colors
HSL is the most intuitive for designers - specify Hue, Saturation, and Lightness:
/* HSL - Hue (0-360°), Saturation (0-100%), Lightness (0-100%) */
/* HUE = Color wheel position (degrees) */
/* 0° = Red, 60° = Yellow, 120° = Green,
180° = Cyan, 240° = Blue, 300° = Magenta */
color: hsl(0, 100%, 50%); /* Red */
color: hsl(120, 100%, 50%); /* Green */
color: hsl(240, 100%, 50%); /* Blue */
color: hsl(220, 90%, 60%); /* Nice blue */
/* SATURATION = Intensity (0% = gray, 100% = vivid) */
color: hsl(0, 0%, 50%); /* Gray (no saturation) */
color: hsl(0, 50%, 50%); /* Muted red */
color: hsl(0, 100%, 50%); /* Vivid red */
/* LIGHTNESS = Brightness (0% = black, 50% = normal, 100% = white) */
color: hsl(0, 100%, 0%); /* Black */
color: hsl(0, 100%, 25%); /* Dark red */
color: hsl(0, 100%, 50%); /* Normal red */
color: hsl(0, 100%, 75%); /* Light red */
color: hsl(0, 100%, 100%); /* White */
/* HSLA - HSL with Alpha transparency */
color: hsla(0, 100%, 50%, 0.5); /* 50% transparent red */
💡 Why HSL is Powerful: Easy to create color variations! Keep hue the same, adjust saturation and lightness for different shades.
/* Same hue (220 = blue), different variations */
--primary: hsl(220, 90%, 50%); /* Main color */
--primary-light: hsl(220, 90%, 70%); /* Lighter */
--primary-dark: hsl(220, 90%, 30%); /* Darker */
--primary-muted: hsl(220, 40%, 50%); /* Less saturated */
3.4 CSS Typography
Typography is one of the most important aspects of web design. Good typography improves readability, establishes visual hierarchy, and creates the right mood for your content. CSS provides extensive control over how text appears.
Font Family
The font-family property specifies which font(s) to use. Always provide
fallbacks!
/* RULE: Always provide fallbacks in case fonts aren't available */
/* Order: Preferred → Fallback → Generic */
body {
font-family: "Helvetica Neue", Arial, sans-serif;
}
/* Fonts with spaces need quotes */
font-family: "Times New Roman", Georgia, serif;
font-family: "Courier New", Consolas, monospace;
/* Generic font families (always last in the list) */
font-family: serif; /* Times-like fonts with serifs */
font-family: sans-serif; /* Clean fonts like Arial, Helvetica */
font-family: monospace; /* Fixed-width fonts for code */
font-family: cursive; /* Handwriting-style fonts */
font-family: fantasy; /* Decorative fonts */
/* Modern system font stack (uses device's native font) */
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
Font Size
Control text size using various units. Prefer relative units for accessibility:
/* Absolute units */
font-size: 16px; /* Pixels - fixed size */
font-size: 12pt; /* Points - print design */
/* Relative units (preferred for accessibility!) */
font-size: 1rem; /* 1x root element size (usually 16px) */
font-size: 1.5rem; /* 1.5x root = 24px */
font-size: 0.875rem; /* 14px */
font-size: 1em; /* 1x parent element size */
font-size: 1.2em; /* 1.2x parent size */
font-size: 100%; /* Same as 1em */
font-size: larger; /* Larger than parent */
font-size: smaller; /* Smaller than parent */
rem for most text. It respects user
browser settings for accessibility!
Font Weight and Style
/* Font weight - boldness (100-900) */
font-weight: 100; /* Thin */
font-weight: 200; /* Extra Light */
font-weight: 300; /* Light */
font-weight: 400; /* Normal (same as 'normal') */
font-weight: 500; /* Medium */
font-weight: 600; /* Semi Bold */
font-weight: 700; /* Bold (same as 'bold') */
font-weight: 800; /* Extra Bold */
font-weight: 900; /* Black (heaviest) */
font-weight: normal; /* = 400 */
font-weight: bold; /* = 700 */
font-weight: lighter; /* One step lighter than parent */
font-weight: bolder; /* One step bolder than parent */
/* Font style */
font-style: normal; /* Regular text */
font-style: italic; /* Italic */
font-style: oblique; /* Slanted (faked italic) */
Text Properties
Control text appearance, alignment, spacing, and decoration:
p {
/* TEXT COLOR */
color: #333; /* Dark gray - good for readability */
/* LINE HEIGHT - spacing between lines */
line-height: 1.6; /* 1.5-1.8 is most readable */
line-height: 24px; /* Can use px too */
/* SPACING */
letter-spacing: 1px; /* Space between letters */
letter-spacing: 0.1em; /* Relative spacing */
word-spacing: 2px; /* Space between words */
/* TEXT ALIGNMENT */
text-align: left; /* Default for LTR languages */
text-align: right; /* Align to right */
text-align: center; /* Center text */
text-align: justify; /* Stretch to fill width */
/* TEXT DECORATION */
text-decoration: none; /* Remove decoration */
text-decoration: underline; /* Underline */
text-decoration: line-through; /* Strikethrough */
text-decoration: overline; /* Line above */
/* TEXT TRANSFORM */
text-transform: uppercase; /* ALL CAPS */
text-transform: lowercase; /* all lowercase */
text-transform: capitalize; /* First Letter Each Word */
text-transform: none; /* Normal case */
/* TEXT INDENT */
text-indent: 2em; /* Indent first line */
/* TEXT SHADOW */
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
/* x-offset y-offset blur-radius color */
}
Web Fonts (Google Fonts)
Use custom fonts from services like Google Fonts:
<!-- In HTML <head> -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
/* Then use in CSS */
body {
font-family: 'Inter', sans-serif;
}
3.5 The CSS Box Model
The Box Model is one of the most fundamental concepts in CSS. Every HTML element is rendered as a rectangular box, and understanding how these boxes work is essential for controlling layout, spacing, and sizing.
The Four Layers of the Box Model
Every box has four layers, from inside to outside:
┌─────────────────────────────────────┐
│ MARGIN (outside) │ ← Space OUTSIDE the border
│ ┌───────────────────────────────┐ │ (separates from other elements)
│ │ BORDER │ │ ← The visible edge
│ │ ┌─────────────────────────┐ │ │
│ │ │ PADDING │ │ │ ← Space INSIDE the border
│ │ │ ┌───────────────────┐ │ │ │ (between border and content)
│ │ │ │ CONTENT │ │ │ │ ← Your actual content
│ │ │ │ (text, images) │ │ │ │ (affected by width/height)
│ │ │ └───────────────────┘ │ │ │
│ │ └─────────────────────────┘ │ │
│ └───────────────────────────────┘ │
└─────────────────────────────────────┘
- Content: The actual content (text, images) - controlled by
widthandheight - Padding: Space INSIDE the border, around the content - has background color
- Border: The visible edge of the element
- Margin: Space OUTSIDE the border - transparent, pushes other elements away
Width and Height
.box {
/* Fixed dimensions */
width: 300px;
height: 200px;
/* Percentage (relative to parent) */
width: 50%; /* Half of parent width */
width: 100%; /* Full parent width */
/* Min and Max constraints */
min-width: 200px; /* Never smaller than 200px */
max-width: 800px; /* Never larger than 800px */
min-height: 100px;
max-height: 500px;
/* Auto - browser calculates */
width: auto; /* Default - fills available space */
height: auto; /* Default - fits content */
}
Padding (Inside Spacing)
Padding adds space between the content and the border. It takes the element's background color.
.box {
/* INDIVIDUAL SIDES */
padding-top: 10px;
padding-right: 20px;
padding-bottom: 10px;
padding-left: 20px;
/* SHORTHAND - most common */
padding: 20px; /* All 4 sides same */
padding: 10px 20px; /* Vertical | Horizontal */
padding: 10px 20px 15px; /* Top | Horizontal | Bottom */
padding: 10px 20px 15px 25px; /* Top | Right | Bottom | Left */
/* Remember: Clockwise from top (TRBL = TRouBLe) */
}
Margin (Outside Spacing)
Margin adds space outside the border, separating the element from others. Margins are transparent.
.box {
/* Same syntax as padding */
margin: 20px; /* All sides */
margin: 10px 20px; /* Vertical | Horizontal */
margin: 10px 20px 15px 25px; /* TRBL */
/* CENTER HORIZONTALLY - very common! */
margin: 0 auto; /* No vertical, auto horizontal */
/* Note: Element must have a width set */
/* Negative margins (pull elements closer) */
margin-top: -10px; /* Overlaps with element above */
}
Border Properties
.box {
/* SHORTHAND - most common */
border: 1px solid #ccc; /* width style color */
border: 2px dashed red;
border: 3px dotted #333;
/* Individual properties */
border-width: 2px;
border-style: solid; /* solid, dashed, dotted, double, none */
border-color: #333;
/* Individual sides */
border-top: 2px solid red;
border-bottom: 1px solid #ccc;
border-left-width: 4px;
/* BORDER-RADIUS - rounded corners */
border-radius: 8px; /* All corners */
border-radius: 50%; /* Perfect circle (if square) */
border-radius: 10px 20px; /* top-left/bottom-right | top-right/bottom-left */
border-radius: 10px 20px 30px 40px; /* Each corner */
}
Box-Sizing (CRITICAL!)
This property changes how width and height are calculated -
it's one of the most
important CSS properties to understand!
/* DEFAULT: content-box */
/* width/height = content ONLY */
/* Total size = width + padding + border */
.box {
box-sizing: content-box;
width: 200px;
padding: 20px;
border: 5px solid;
/* Actual width: 200 + 40 + 10 = 250px! */
}
/* BETTER: border-box */
/* width/height = content + padding + border */
/* Total size = width (exactly what you set!) */
.box {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid;
/* Actual width: 200px (content shrinks to fit) */
}
/* BEST PRACTICE: Apply to all elements */
*, *::before, *::after {
box-sizing: border-box;
}
border-box! It makes layout much easier because
elements are exactly the size you specify.
3.6 Backgrounds
CSS provides extensive control over element backgrounds - from simple colors to complex multi-layered images and gradients. Backgrounds are fundamental to visual design.
Background Color
.box {
/* Solid colors - any color format works */
background-color: #f5f5f5; /* Hex */
background-color: rgb(245, 245, 245);
background-color: hsl(0, 0%, 96%);
background-color: lightgray; /* Named */
/* Transparent backgrounds */
background-color: transparent;
background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent */
}
Background Images
.hero {
/* Load image from URL */
background-image: url('images/hero.jpg');
background-image: url('../images/bg.png'); /* Relative path */
background-image: url('https://example.com/image.jpg'); /* Absolute */
/* REPEAT - how image tiles */
background-repeat: repeat; /* Tile both ways (default) */
background-repeat: no-repeat; /* Don't tile */
background-repeat: repeat-x; /* Tile horizontally */
background-repeat: repeat-y; /* Tile vertically */
/* POSITION - where image sits */
background-position: center center; /* Centered */
background-position: top left; /* Keywords */
background-position: 50% 50%; /* Percentage */
background-position: 100px 50px; /* Pixels */
/* SIZE - how image scales */
background-size: auto; /* Original size (default) */
background-size: cover; /* Fill container, may crop */
background-size: contain; /* Fit inside, may leave space */
background-size: 100% 100%; /* Stretch to fill */
background-size: 200px; /* Fixed width */
/* ATTACHMENT - scroll behavior */
background-attachment: scroll; /* Scrolls with content (default) */
background-attachment: fixed; /* Fixed (parallax effect) */
}
CSS Gradients
Gradients are smooth transitions between colors - they're created with CSS, no images needed!
.box {
/* Basic: top to bottom */
background: linear-gradient(red, blue);
/* With direction */
background: linear-gradient(to right, red, blue);
background: linear-gradient(to bottom right, red, blue);
background: linear-gradient(45deg, red, blue); /* Angle */
/* Multiple color stops */
background: linear-gradient(to right, red, orange, yellow, green);
/* With position stops */
background: linear-gradient(to right, red 0%, blue 50%, green 100%);
/* Beautiful examples */
background: linear-gradient(to right, #3b82f6, #8b5cf6); /* Blue-Purple */
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.box {
/* Basic: center outward */
background: radial-gradient(white, black);
/* Shape */
background: radial-gradient(circle, white, black);
background: radial-gradient(ellipse, white, black);
/* Position */
background: radial-gradient(circle at top left, white, black);
}
Background Shorthand
/* Order: color image repeat position/size */
background: #f5f5f5 url('bg.jpg') no-repeat center/cover;
/* Multiple backgrounds (layered, first is on top) */
background:
linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)),
url('hero.jpg') center/cover;
/* Creates a darkened hero image! */
3.7 CSS Units
Understanding CSS units is essential for creating responsive, accessible designs. Different units serve different purposes - choosing the right one matters!
Absolute Units
Absolute units are fixed sizes that don't change based on other elements:
/* PIXELS (px) - Most common absolute unit */
width: 100px; /* Fixed size, doesn't scale */
font-size: 16px;
border: 1px solid;
/* Print units (rarely used for screens) */
width: 1in; /* 1 inch = 96px */
width: 2.54cm; /* 1 cm ≈ 38px */
width: 25.4mm; /* Millimeters */
width: 12pt; /* Points (1pt = 1/72 inch) */
When to use pixels: Borders, box-shadows, very small fixed values, when you need exact control.
Relative Units - Font-Based
These units scale based on font sizes - great for accessibility!
/* EM - relative to PARENT element's font-size */
.parent { font-size: 20px; }
.child {
font-size: 1.5em; /* = 30px (1.5 × 20px) */
padding: 1em; /* = 30px (uses element's own font-size) */
}
/* ⚠️ Problem: em compounds (multiplies) in nested elements! */
.grandchild {
font-size: 1.5em; /* = 45px! (1.5 × 30px) */
}
/* REM - relative to ROOT (html) element's font-size */
/* Much more predictable! */
html { font-size: 16px; } /* Default in most browsers */
.any-element {
font-size: 1rem; /* = 16px */
font-size: 1.5rem; /* = 24px */
font-size: 0.875rem; /* = 14px */
margin: 2rem; /* = 32px */
}
/* 💡 REM doesn't compound - always relative to root! */
rem for most sizes. It respects user
browser settings and scales consistently!
Relative Units - Viewport-Based
These units are relative to the browser viewport (visible screen area):
/* VW - viewport width (1vw = 1% of viewport width) */
width: 100vw; /* Full viewport width */
width: 50vw; /* Half viewport width */
font-size: 5vw; /* Text scales with window width */
/* VH - viewport height (1vh = 1% of viewport height) */
height: 100vh; /* Full viewport height (full screen!) */
min-height: 100vh; /* At least full screen */
/* VMIN - % of smaller dimension */
font-size: 5vmin; /* Scales nicely on any orientation */
/* VMAX - % of larger dimension */
font-size: 5vmax;
/* Common patterns */
.hero {
height: 100vh; /* Full-screen hero section */
}
.full-width {
width: 100vw;
margin-left: calc(-50vw + 50%); /* Break out of container */
}
Percentage (%)
/* Percentage - relative to PARENT element */
.parent { width: 800px; }
.child {
width: 50%; /* = 400px (50% of parent) */
width: 100%; /* = 800px (full parent width) */
}
/* For height %, parent MUST have explicit height! */
.parent { height: 500px; }
.child { height: 50%; } /* = 250px */
When to Use What?
/* FONT SIZES: rem (best), px (okay) */
font-size: 1rem; /* Respects user settings ✓ */
/* SPACING (margin, padding): rem or em */
padding: 1.5rem; /* Scales with root font */
margin: 1em; /* Scales with element's font */
/* WIDTHS: %, vw, or max-width with px */
width: 100%; /* Flexible */
max-width: 1200px; /* With constraint */
/* HEIGHTS: vh for full-screen, auto otherwise */
min-height: 100vh; /* Full viewport */
/* BORDERS/SHADOWS: px (small, precise values) */
border: 1px solid;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
Exercise: Style a Button
Write CSS to create a styled button with:
- Blue background color (
#3b82f6) - White text
- Padding of
12px 24px - Rounded corners (
8px) - No border