Unit 4 — CSS3 Styling & Responsive Web Design
1. Introduction to CSS3 & Implementation Types
CSS (Cascading Style Sheets) is the declarative style language used to describe the presentation, visual aesthetics, formatting, and layout of an HTML document. CSS3 introduced modular specifications, bringing native layout systems (Flexbox, Grid), media queries for responsive design, gradients, rounded corners, transitions, and hardware-accelerated animations.
1.1 CSS Syntax Anatomy
A CSS rule-set consists of a selector and a declaration block:
selector {
property: value; /* declaration */
property: value;
}
- Selector: Targets the specific HTML element(s) to style (e.g.,
h1,.card,#hero). - Declaration Block: Contained within curly braces
{}. - Property: The style attribute to change (e.g.,
color,font-size,margin). - Value: The specific setting applied to that property, terminated by a semicolon
;.
1.2 The Three Types of CSS Implementation
| Implementation Type | Syntax / Method | Advantages | Disadvantages | Best Used For |
|---|---|---|---|---|
| Inline CSS | style attribute directly on element: <p style="color: red;"> |
Highest specificity in normal CSS; fast for quick testing. | Clutters HTML; unmaintainable; violates separation of concerns; no caching. | Emergency overrides or single email templates. |
| Internal CSS | Placed inside <style> tags within the <head> section. |
Applies to the entire single page; no extra HTTP request needed. | Cannot style multiple HTML documents; inflates HTML file size. | Unique single-page layouts or landing pages. |
| External CSS (Recommended) | Linked via <link rel="stylesheet" href="style.css"> in <head>. |
Separation of concerns; styles whole site from one file; cached by browser for speed. | Requires an additional network request on first load (mitigated by HTTP/2). | Standard professional web development. |
2. CSS Selectors & Specificity Hierarchy
Selectors determine which elements in the DOM tree receive style declarations.
2.1 Complete Selectors Inventory
| Selector Type | Syntax Example | Targets |
|---|---|---|
| Universal Selector | * |
Every element in the entire document. |
| Type / Element Selector | p, h1, table |
All elements matching that tag name. |
| Class Selector | .btn, .card |
All elements having that class attribute (class="btn"). |
| ID Selector | #header, #main-nav |
The single unique element with that ID (id="header"). |
| Grouping Selector | h1, h2, h3 |
Groups multiple selectors sharing identical declarations. |
| Descendant Combinator | nav a |
Any <a> inside <nav> at any nesting depth. |
| Child Combinator | ul > li |
Direct children only (only <li> immediately inside <ul>). |
| Adjacent Sibling | h2 + p |
The first <p> immediately following an <h2>. |
| General Sibling | h2 ~ p |
All <p> elements following an <h2> that share the same parent. |
| Attribute Selector | input[type="text"] |
Elements with a matching attribute value. |
| Substring Attribute | a[href^="https"] |
Anchors whose href begins with "https". |
2.2 CSS Specificity Formula $(A, B, C, D)$
When conflicting CSS rules target the same element, the browser calculates specificity to determine which rule wins:
- Inline styles ($A$):
style=""attribute has weight $1000$ (1, 0, 0, 0). - IDs ($B$): Each
#idselector contributes $100$ (0, 1, 0, 0). - Classes, Pseudo-classes, Attributes ($C$):
.class,:hover,[type="text"]contribute $10$ (0, 0, 1, 0). - Elements & Pseudo-elements ($D$):
div,p,::beforecontribute $1$ (0, 0, 0, 1). - Universal (
*) & Inherited styles: Contribute $0$ (0, 0, 0, 0).
Comparison Example:
p { color: black; } /* Specificity: (0, 0, 0, 1) = 1 */
.content p { color: blue; } /* Specificity: (0, 0, 1, 1) = 11 */
#main .content p { color: green; } /* Specificity: (0, 1, 1, 1) = 111 -> WINS! */
[!NOTE]
!importantoverrides normal specificity entirely. However, overusing!importantbreaks the cascade and makes stylesheets notoriously difficult to debug.
3. CSS Units, Colors, Typography & Gradients
3.1 CSS Units: Absolute vs. Relative
- Absolute Units: Fixed physical dimensions, not responsive:
px(Pixels): 1px = 1/96th of an inch. Precise, but does not adapt to user browser font preferences.pt(Points): Primarily used for print stylesheets (1pt = 1/72 inch).
- Relative Units: Scale dynamically relative to another reference:
%(Percentage): Relative to the parent element's dimension.em: Relative to the font-size of the element itself (or parent font-size).rem(Root EM): Relative to the font-size of the root<html>element (default 16px). Best practice for scalable typography & spacing.vw(Viewport Width): $1\text{vw} = 1\%$ of the browser viewport width.vh(Viewport Height): $1\text{vh} = 1\%$ of the browser viewport height.
3.2 Color Models in CSS
- Named Colors:
red,blue,transparent. - HEX (Hexadecimal):
#RRGGBBor#RRGGBBAA(e.g.,#2563eb,#00000080for 50% opacity). - RGB / RGBA:
rgb(37, 99, 235)orrgba(37, 99, 235, 0.5)(Red, Green, Blue from 0–255; Alpha opacity from 0.0 to 1.0). - HSL / HSLA:
hsl(221, 83%, 53%)(Hue 0–360°, Saturation 0–100%, Lightness 0–100%).
3.3 Typography Essentials
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 1rem; /* 16px */
font-weight: 400; /* Regular */
line-height: 1.6; /* 160% of font size for optimal reading */
letter-spacing: 0.02em;
text-align: left;
}
3.4 CSS Gradients
- Linear Gradient: Transitions colors along a straight line:
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%); - Radial Gradient: Radiates outwards from a central point:
background: radial-gradient(circle at center, #ff9a9e 0%, #fecfef 99%);
4. The CSS Box Model & Display Modes
Every HTML element rendered in a browser is enclosed in a rectangular box consisting of four concentric layers:
+-------------------------------------------------+
| MARGIN |
| +-----------------------------------------+ |
| | BORDER | |
| | +---------------------------------+ | |
| | | PADDING | | |
| | | +-------------------------+ | | |
| | | | CONTENT | | | |
| | | | Width x Height | | | |
| | | +-------------------------+ | | |
| | +---------------------------------+ | |
| +-----------------------------------------+ |
+-------------------------------------------------+
4.1 The Four Box Model Layers
- Content: The innermost area where text, images, or child elements appear (
widthandheight). - Padding: Transparent space clearing the area between content and border (
padding: 1rem). - Border: A stroke wrapping around padding and content (
border: 1px solid #e2e8f0). - Margin: Transparent space outside the border separating this element from adjacent neighbors.
4.2 The Critical Reset: box-sizing: border-box
- Default
content-box: Total element width = $\text{width} + \text{padding-left} + \text{padding-right} + \text{border-left} + \text{border-right}$. An element withwidth: 100%pluspadding: 20pxoverflows its parent container! - Modern Standard
border-box: Padding and borders are absorbed inside the declared width.
/* Universal Box Model Reset (Standard in Modern Web Design) */
*, *::before, *::after {
box-sizing: border-box;
}
4.3 Display Modes Compared
| Value | Line Behavior | Width / Height Applicable? | Margins & Padding |
|---|---|---|---|
block |
Starts on a new line; stretches full width available (<div>, <p>, <h1>). |
Yes | Fully applicable on all 4 sides. |
inline |
Sits inline on the same line as adjacent text (<span>, <a>, <strong>). |
No | Left/right work; top/bottom do not affect vertical layout. |
inline-block |
Sits inline with text, but behaves as a block internally (<button>, <img>). |
Yes | Fully applicable on all 4 sides. |
none |
Completely removes element from the visual DOM flow (takes 0 space). | N/A | N/A |
flex |
Establishes a 1-dimensional flex container for immediate children. | Yes | Manages children distribution dynamically. |
5. CSS Positioning & Stacking Context
The position property defines how an element is placed relative to the viewport, parent, or document flow:
position: static(Default): Normal document flow;top,bottom,left,right, andz-indexhave no effect.position: relative: Positioned relative to its normal position in the flow. Shifting it does not affect adjacent elements, and it acts as an anchor parent for absolute children.position: absolute: Removed entirely from normal flow; positioned relative to the nearest positioned ancestor (an ancestor withrelative,absolute, orfixed).position: fixed: Removed from normal flow; positioned relative to the browser viewport. Remains locked in place during scrolling (e.g., sticky headers, floating action buttons).position: sticky: Hybrid mode: behaves asrelativeuntil the user scrolls past a specified threshold (e.g.,top: 0), then "sticks" in place likefixed.z-index: Specifies the stack level of positioned elements along the 3D Z-axis. Higher values sit atop lower values.
6. Modern CSS Flexbox Architecture
CSS Flexbox (Flexible Box Layout) is a 1-dimensional layout model designed to distribute space and align items along a horizontal row or vertical column, accommodating varying screen sizes automatically.
MAIN AXIS (flex-direction: row)
+--------------------------------------------->
+-----+---------------------------------------------+
| | +--------+ +--------+ +--------+ |
CROSS | | | Item 1 | | Item 2 | | Item 3 | |
AXIS | | +--------+ +--------+ +--------+ |
v +---------------------------------------------+
6.1 Flex Container Properties (Parent)
| Property | Values | Description |
|---|---|---|
display |
flex, inline-flex |
Activates flex context for direct child elements. |
flex-direction |
row (default), row-reverse, column, column-reverse |
Defines the main axis direction. |
flex-wrap |
nowrap (default), wrap, wrap-reverse |
Allows items to wrap onto multiple lines if space runs out. |
justify-content |
flex-start, center, flex-end, space-between, space-around, space-evenly |
Aligns items along the main axis. |
align-items |
stretch (default), flex-start, center, flex-end, baseline |
Aligns items along the cross axis. |
gap |
1rem, 10px 20px |
Native spacing between flex items without margin hacks. |
6.2 Flex Item Properties (Children)
| Property | Syntax / Value | Description |
|---|---|---|
flex-grow |
0 (default), 1, 2 |
Ability for a flex item to grow if extra free space is available. |
flex-shrink |
1 (default), 0 |
Ability for an item to shrink when space is insufficient. 0 prevents shrinking. |
flex-basis |
auto (default), 200px, 25% |
The initial default size of the item before remaining space is distributed. |
flex (Shorthand) |
flex: 1 1 auto; |
Combines flex-grow, flex-shrink, and flex-basis. |
align-self |
auto, flex-start, center, flex-end |
Overrides the container's align-items for this individual item. |
order |
0 (default), 1, -1 |
Controls the visual order of items without altering HTML source code. |
Production Flexbox Card Row Example:
<div class="card-container">
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
</div>
<style>
.card-container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: stretch;
gap: 1.5rem;
flex-wrap: wrap;
}
.card {
flex: 1 1 300px; /* Grow, shrink, base width 300px */
background: #ffffff;
padding: 1.5rem;
border-radius: 8px;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}
</style>
7. Responsive Web Design (RWD) & Media Queries
Responsive design ensures web layouts dynamically adapt to the screen size, orientation, and resolution of any device (smartphones, tablets, laptops, ultra-wide monitors).
7.1 The Responsive Viewport Meta Tag
<meta name="viewport" content="width=device-width, initial-scale=1.0">
width=device-width: Sets viewport width to the physical screen width of the device.initial-scale=1.0: Sets initial 100% zoom level upon opening.
7.2 Media Queries Syntax & Breakpoints
Media queries allow conditional application of CSS styles based on device characteristics:
/* Base styles: Mobile-First default (Phones < 768px) */
.content-grid {
display: flex;
flex-direction: column;
}
/* Tablet Breakpoint (min-width: 768px) */
@media screen and (min-width: 768px) {
.content-grid {
flex-direction: row;
}
}
/* Desktop Breakpoint (min-width: 1024px) */
@media screen and (min-width: 1024px) {
.container {
max-width: 1200px;
margin: 0 auto;
}
}
7.3 Standard Responsive Breakpoints (W3Schools / Bootstrap Industry Standard)
- Extra Small (Phones):
< 576px - Small (Landscape phones):
≥ 576px - Medium (Tablets):
≥ 768px - Large (Desktops):
≥ 992px - Extra Large (Wide screens):
≥ 1200px
8. Transitions, Transforms & Keyframe Animations
8.1 2D & 3D Transforms
The transform property alters the visual coordinate space of an element without reflowing the document:
transform: translate(x, y): Moves element along X and Y axes.transform: rotate(45deg): Rotates element around its transform origin.transform: scale(1.05): Zooms element in or out.transform: skew(10deg): Distorts element along an angle.
8.2 CSS Transitions
Smoothly animates changes between two property states (e.g., default and :hover):
.button {
background-color: #2563eb;
color: #fff;
padding: 0.75rem 1.5rem;
border-radius: 6px;
/* property duration timing-function delay */
transition: background-color 0.25s ease, transform 0.2s ease;
}
.button:hover {
background-color: #1d4ed8;
transform: translateY(-2px);
}
8.3 CSS Keyframe Animations (@keyframes)
Allows complex, multi-stage, recurring animations without JavaScript:
@keyframes pulseGlow {
0% {
transform: scale(1);
box-shadow: 0 0 0 0 rgba(37, 99, 235, 0.4);
}
50% {
transform: scale(1.03);
box-shadow: 0 0 15px 4px rgba(37, 99, 235, 0.6);
}
100% {
transform: scale(1);
box-shadow: 0 0 0 0 rgba(37, 99, 235, 0);
}
}
.status-badge-active {
animation: pulseGlow 2s infinite ease-in-out;
}
9. Pseudo-Classes & Pseudo-Elements
- Pseudo-classes (
:) select elements based on a dynamic state or DOM index:- User Action:
:hover,:active,:focus,:focus-visible. - Structural:
:first-child,:last-child,:nth-child(even),:nth-child(3n+1). - Form State:
:checked,:disabled,:valid,:invalid.
- User Action:
- Pseudo-elements (
::) style specific parts of an element or inject virtual content:::before/::after: Injects cosmetic content before/after element content (mandatorycontent: ""property).::selection: Styles the highlighted text selection.::first-letter: Styles the opening initial drop-cap letter.
10. Unit 4 Review & Exam Revision Checklist
- Specificity Score: Calculate $(A, B, C, D)$ for complex selectors on exam questions.
- Box Model Calculation: Explain
content-boxvsborder-boxwith arithmetic dimensions. - Flexbox Mastery: Memorize container properties (
justify-contentvsalign-items) and item properties (flex: 1 1 auto). - Media Queries: Write standard
@media screen and (min-width: 768px)syntax from memory. - Transforms vs Transitions vs Animations: Clearly differentiate property triggering, duration, and
@keyframes.