Unit 4: CSS Styling & Layouts
Interactive First-Principles Rendering Engine
- Write CSS selectors including element, class, id, descendant, child, and pseudo-classes
- Understand the box model (content, padding, border, margin) and how it affects layout
- Use the display property (block, inline, inline-block, none) and float for basic layouts
- Apply backgrounds, borders, colors, and opacity to style page elements
0. CSS Syntax — How to Read & Write a Rule
The one shape every CSS rule follows (skeleton):
selector {
property: value;
property: value;
}
Semantic — read it as a sentence: the selector picks which element(s) to style; inside the { } block, each property: value; is one declaration — the property is what you change and the value is to what. Declarations end with a semicolon ;; the last one's semicolon is optional but keep it. CSS ignores extra whitespace and line breaks.
- Selector —
p,.card,#header, or any pattern from Lesson 1. - Property — the CSS feature:
color,font-size,margin… (always lowercase, words joined by-). - Value — what you set it to:
red,16px,20px. Many values need units (px,em,%); colors can be names,#hex, orrgb(). - Comments —
/* anything between these is ignored */.
1. CSS Selectors — Complete Reference
CSS Selectors are patterns used to select HTML elements for styling. The browser evaluates selector specificity to decide which rule wins when multiple rules match the same element.
Three ways to apply CSS (priority order):- Inline:
<div style="color:red">— highest priority - Internal:
<style>block in<head> - External:
.cssfile via<link>— best practice
| Selector | Example | Targets | Specificity |
|---|---|---|---|
| Element | div { } | All <div> elements | 0,0,1 |
| Class | .btn { } | Elements with class="btn" | 0,1,0 |
| ID | #header { } | Element with id="header" | 1,0,0 |
| Descendant | div p { } | <p> inside <div> | 0,1,2 |
| Child | div > p { } | Direct <p> child of <div> | 0,1,2 |
| Adjacent Sibling | h2 + p { } | <p> immediately after <h2> | 0,1,2 |
| Attribute | [type="text"] { } | Elements with type="text" | 0,1,0 |
| Pseudo-class | a:hover { } | Links on hover | 0,1,0 |
| Pseudo-element | p::first-line { } | First line of <p> | 0,0,1 |
| Universal | * { } | Every element | 0,0,0 |
Specificity Calculator
Specificity is computed as a 3-part value: (ID count, Class count, Element count). Inline styles always win. !important overrides everything (use sparingly).
box-sizing Confusion
By default (content-box), width only sets the content width — padding and border add to it. A width:200px div with padding:20px + border:5px is actually 250px wide. Use box-sizing: border-box to include padding and border in the declared width.
width × height
2. The CSS Box Model Simulator
- Content (Height/Width): The core area containing text or images.
- Padding: Transparent space inside the border, pushing content inward.
- Border: The solid line wrapped around the padding.
- Margin: Invisible space outside the border, pushing other elements away.
- Outline: Similar to a border, but drawn outside the element's dimensions. It does not affect the layout or push other elements (useful for accessibility focus rings).
Manipulate Box Geometry
content-box: width = content only. border-box: width = content + padding + border.
(Content)
/* CSS for Box Model Visual */
#targetBox {
background-color: var(--blue-500);
color: white;
font-weight: bold;
padding: 20px;
border: 5px solid #fde047;
width: 150px;
margin: 20px;
box-sizing: content-box;
}
/* JavaScript to update values on slider change */
function updateBox() {
const pad = document.getElementById('padInput').value;
const brd = document.getElementById('brdInput').value;
const mar = document.getElementById('marInput').value;
const wid = document.getElementById('widInput').value;
document.getElementById('padVal').innerText = pad + 'px';
document.getElementById('brdVal').innerText = brd + 'px';
document.getElementById('marVal').innerText = mar + 'px';
document.getElementById('widVal').innerText = wid + 'px';
const target = document.getElementById('targetBox');
const useBorderBox = document.getElementById('boxSizingToggle').checked;
target.style.padding = pad + 'px';
target.style.borderWidth = brd + 'px';
target.style.width = wid + 'px';
target.style.margin = mar + 'px';
target.style.boxSizing = useBorderBox ? 'border-box' : 'content-box';
}
3. Before & After — CSS Makes the Difference
Toggle between unstyled HTML and the same HTML with CSS applied. This demonstrates why CSS is essential for visual design.
Student Profile
Name: John Doe | Branch: CSE | Semester: 5
- Web Designing: A+
- Data Structures: A
- DBMS: B+
4. CSS Colors, Backgrounds & Fonts Quick Reference
CSS provides multiple ways to specify colors: named colors, HEX, RGB, RGBA, HSL, HSLA. The background property is a shorthand for background-color, image, repeat, position, and size.
font-family — Typeface (e.g., system-ui, serif, monospace)
font-size — Size in px, em, rem, %
font-weight — Thickness (normal: 400, bold: 700)
line-height — Vertical spacing between lines
text-align — left, center, right, justify
text-decoration — underline, line-through, none
Pick a color or type a HEX value. Every equivalent format updates live.
5. Document Flow: Display, Float & Overflow
display: Changes the fundamental behavior of the node (block, inline, none).float: Removes the element from normal flow, pushing it left or right. Text wraps around it.clear: Forces an element to drop below any floated elements (resolves layout breaking).overflow: Dictates what happens when content is larger than its parent container's dimensions.
Manipulate Target Element
Block (Full width)
Inline (Content width)
None (Hidden)
None
Float Left
Float Right
Visible (Bleeds out)
Hidden (Clipped)
Scroll (Adds scrollbar)
Display & Float Output
Overflow Output
Line 2 data...
Line 3 data...
Line 4 data...
Line 5 data...
Line 6 data...
<!-- HTML Structure -->
<div class="layout-stage">
<span>Some preceding inline text. </span>
<div class="layout-item" id="interactiveLayoutBox">TARGET ELEMENT</div>
<span> This is subsequent text. </span>
<div style="clear: both;">...</div>
</div>
/* CSS Display Property Values */
/* block - full width, starts on new line */
/* inline - content width, flows inline */
/* inline-block - flows inline, respects width/height */
/* none - removed from layout */
/* JavaScript to switch display/float */
function updateLayout() {
const target = document.getElementById('interactiveLayoutBox');
const displayVal = document.querySelector('input[name="display"]:checked').value;
const floatVal = document.querySelector('input[name="float"]:checked').value;
target.style.display = displayVal;
target.style.float = floatVal;
}
6. Position — Taking Elements Out of Flow
Anatomy: position controls placement. static (default) follows normal flow; relative nudges from its spot but keeps its space; absolute is placed relative to the nearest positioned ancestor; fixed sticks to the viewport; sticky switches between relative and fixed on scroll. Combine with top/right/bottom/left, and use z-index to control stacking.
7. Flexbox — One-Dimensional Layout
Anatomy + intent: display: flex arranges children along a single axis. flex-direction sets that axis, justify-content aligns along it, align-items aligns across it, gap spaces items, and flex-wrap allows multiple lines. Prefer Flexbox over float for nav bars, card rows, and centering.
8. CSS Grid — Two-Dimensional Layout
Anatomy + intent: display: grid places children in rows and columns at once. Define tracks with grid-template-columns/rows (try 1fr, auto, or fixed px), space them with gap, and align items with justify-items/align-items. Use Grid for full page layouts and component grids.
Flexbox (§7) and Grid (§8) above now have live sandboxes — explore them first. For truly reusable components, go further with container queries, which respond to a parent's size rather than the viewport:
Container Queries (Modern)
Unlike media queries that respond to the viewport, container queries respond to a parent element's size. This enables truly reusable components:
.card-container { container-type: inline-size; }
@container (min-width: 400px) {
.card { flex-direction: row; }
}
Browser support for container queries is over 90% as of 2025. Use them instead of media queries for component-level responsiveness.