Unit 3: Cascading Style Sheets
I. Orientation: CSS as a Declarative Presentation Language
CSS (proposed by Håkon Wium Lie, 1994; CSS Level 1 became a W3C Recommendation in December 1996, CSS 2.1 in 2011, after which the language split into independently versioned modules) separates presentation from the structure supplied by HTML. A stylesheet is a list of declarative rules; the browser matches them against the document tree and resolves conflicts algorithmically rather than procedurally.
- Rule syntax:
selector { property: value; }— e.g.h1 { color: navy; }. The selector chooses elements, the declaration block sets values, and every declaration ends with;. - Three insertion methods: inline (
<p style="color:red">), internal (<style>in<head>), external (<link rel="stylesheet" href="main.css">). External is preferred: one file cached across pages. - The cascade (origin → specificity → source order): author styles beat user-agent defaults; within the same origin the more specific selector wins; ties go to the last declaration.
!importantjumps above normal declarations of the same origin. - Inheritance: typography-related properties (
color,font-family,line-height) inherit to descendants; box properties (margin,border,width) do not.inherit,initialandunsetforce the behaviour explicitly. - At-rules:
@import,@media,@font-face,@keyframes— statements that carry their own blocks or parameters. - Every element generates a box: all layout in later sections is the arrangement of these boxes, controlled by
display.
II. Selection: Targeting Elements Precisely
A. CSS Selectors and Specificity
Selectors match nodes in the document tree; specificity is the numeric tiebreaker when two rules set the same property.
- Simple selectors: type (
p), class (.card), ID (#nav), universal (*). - Combinators: descendant (
div p), child (ul > li), adjacent sibling (h2 + p), general sibling (h2 ~ p). - Specificity triple (a, b, c): a = IDs, b = classes/attributes/pseudo-classes, c = element types/pseudo-elements.
#nav li.active a→ (1, 1, 2);ul li a→ (0, 0, 3). The first wins regardless of order.
- Non-competing values:
*and combinators contribute 0; inlinestyleoutranks any selector;!importantoutranks inline. - Grouping:
h1, h2, h3 { margin: 0; }applies one block to a comma-separated list.
B. Pseudo Classes
A pseudo-class selects an element by state or tree position rather than by markup.
- Link/user states:
:link,:visited,:hover,:focus,:active— written in LVHA order so later rules are not masked. - Structural:
:first-child,:last-child,:nth-child(2n+1)(odd rows),:nth-of-type(),:only-child,:empty,:root. - Functional/logical:
:not(.disabled),:is(h1, h2). - Form states:
:checked,:disabled,:required,:valid,:invalid,:focus-within.
C. Pseudo Elements
A pseudo-element styles a sub-part of an element that has no markup of its own; CSS3 marks them with ::.
blockquote::before { content: "\201C"; font-size: 2rem; }- Generated content:
::before/::afterrequire acontentvalue (may be"") and are used for icons, decorative quotes and clearfix. - Text fragments:
::first-letter(drop caps),::first-line. - UI fragments:
::selection(highlight colour),::placeholder(input hint text),::marker(list bullet).
D. Attribute Selectors
These match on the presence or the string pattern of an attribute value, giving CSS hooks without extra classes.
- Presence and exact:
[disabled],[type="email"]. - Word/prefix list:
[class~="btn"](space-separated word),[lang|="en"](valueenoren-…). - Substring matching:
[href^="https"](starts with),[src$=".pdf"](ends with),[title*="sale"](contains). - Case-insensitive flag:
[href$=".PDF" i].
III. Values, Colour and Type
A. Colors and Backgrounds
Colour values may be given in four notations, and every element can carry layered background images.
- Notations: keyword (
tomato), hex#RRGGBB/#RGB,rgb(255 99 71),rgba(255,99,71,0.5),hsl(9, 100%, 64%)— hue 0–360°, saturation and lightness in %. - Background longhands:
background-color,background-image: url(bg.jpg),background-repeat: no-repeat,background-position: center top,background-size: cover | contain,background-attachment: fixed. - Shorthand:
background: #eee url(hero.jpg) no-repeat center / cover; - Gradients count as images:
background: linear-gradient(to right, #000, #fff);alsoradial-gradient().
B. Units and Measurements
Lengths are absolute (fixed physical mapping) or relative (computed against another value).
- Absolute:
px(the CSS reference pixel),pt= 1/72 in,in= 96px,cm,mm. - Font-relative:
em= current element's font-size;rem= root font-size (usually 16px, so1.5rem= 24px);ch,ex. - Viewport-relative:
vw,vh(1% of viewport width/height),vmin,vmax. - Percentages: resolved against the containing block —
width:50%of parent width, butpadding-top:10%also of parent width. - Functions:
calc(100% - 2rem),min(),max(),clamp(1rem, 2.5vw, 2rem).
C. Typography
Type properties control the font resource and its metrics.
font-family: a stack ending in a generic family —font-family: "Segoe UI", Helvetica, sans-serif;font-size/font-weight/font-style: keywords or lengths; weights 100–900 (400= normal,700= bold);italic/oblique.line-height: prefer unitless (1.5) so descendants scale from their own size.- Shorthand order:
font: italic 700 1rem/1.4 Georgia, serif; - Web fonts:
@font-face { font-family:"Inter"; src:url(inter.woff2) format("woff2"); font-display: swap; }
D. Text Styling
These properties shape the rendered text block rather than the glyph source.
- Alignment and flow:
text-align: left|center|justify,text-indent: 2em,direction,white-space: nowrap|pre,overflow-wrap: break-word. - Decoration and case:
text-decoration: underline dotted red,text-transform: uppercase|capitalize. - Spacing and depth:
letter-spacing: 0.05em,word-spacing,text-shadow: 1px 1px 3px rgba(0,0,0,.4).
IV. Boxes and Positioning
A. Box Model
Every box is four nested rectangles: content, padding, border, margin.
total width (content-box) = width + padding-L/R + border-L/Rbox-sizing:content-box(default) adds padding/border outsidewidth;border-boxincludes them, sowidth:200px; padding:20pxstill occupies 200px.*{box-sizing:border-box}is a standard reset.- Margins: shorthand
margin: 10px 20px(vertical, horizontal);margin: 0 autocentres a block with a set width; adjacent vertical margins collapse to the larger value. - Borders and rounding:
border: 1px solid #ccc,border-radius: 8px, plus non-box shadowbox-shadow: 0 2px 4px rgba(0,0,0,.2). display:block(full width, respects height),inline(ignores width/height and vertical margins),inline-block,none(removed from flow),flex,grid.overflow:visible|hidden|scroll|autocontrols content larger than the box.
B. Positioning Techniques
position changes which box a element is offset from and whether it stays in normal flow.
- In-flow:
static(default, offsets ignored) andrelative(offset from its own position bytop/left, original space preserved; also establishes a containing block). - Out-of-flow:
absolute(offset from nearest positioned ancestor, space collapses),fixed(offset from the viewport, ignores scrolling),sticky(relative until a threshold, then fixed —position:sticky; top:0).- Stacking:
z-indexapplies only to positioned or flex/grid items; higher values paint on top within the same stacking context. - Floats:
float: left|rightremoves a box from normal flow horizontally;clear: bothor a moderndisplay:flow-rootcontainer contains it.
- Stacking:
V. Modern Layout Systems
A. Flexbox Layout
A one-dimensional model distributing space along a main axis.
- Container:
display: flex,flex-direction: row|column,flex-wrap: wrap,justify-content: space-between(main axis),align-items: center(cross axis),align-content,gap: 1rem. - Items:
flex: <grow> <shrink> <basis>—flex: 1means1 1 0%, so items share space equally;align-selfoverrides the container;orderre-sequences visually. - Typical use: navigation bars, toolbars, equal-height cards, vertical centring (
display:flex; justify-content:center; align-items:center).
B. CSS Grid Layout
A two-dimensional model defining rows and columns explicitly.
.wrap {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
grid-template-rows: auto 1fr auto;
gap: 16px;
}
.hero { grid-column: 1 / span 2; }- Sizing:
frdistributes free space;minmax(min,max)bounds a track;auto-fit/auto-fillwithrepeat()produce responsive column counts without media queries. - Placement: by line number (
grid-row: 2 / 4), byspan, or by name usinggrid-template-areaswith matchinggrid-areavalues. - Implicit grid: rows created beyond the template are sized by
grid-auto-rows. - Division of labour: Grid for the page skeleton (both axes), Flexbox for the contents of each cell.
VI. Components and Theming
A. Form Styling
Form controls have platform-specific default rendering, so styling means overriding the user agent.
- Targeting:
input[type="text"], select, textarea { padding:.5rem; border:1px solid #bbb; border-radius:4px; }— attribute selectors are essential because allinputs share one tag name. - Resetting native chrome:
appearance: nonefor custom checkboxes, selects and range sliders;font: inheritbecause controls do not inherit fonts. - State feedback:
:focus-visible { outline: 2px solid #06c; }(never remove focus outlines without replacement),input:invalid { border-color: crimson; },input:checked + label. - Structure: style
label,fieldsetandlegendfor grouping; setbox-sizing:border-boxsowidth:100%fields do not overflow.
B. CSS Variables
Custom properties store reusable values in the cascade itself, unlike preprocessor variables resolved at compile time.
:root { --brand: #0066cc; --gap: 16px; }
.btn { background: var(--brand); padding: var(--gap); }
.dark { --brand: #6ab7ff; } /* re-theme by scope */- Declaration: any property beginning
--; usage viavar(--name, fallback). - Inheritance and scoping: values inherit, so redefining
--brandon an ancestor retints the subtree — the basis of dark-mode theming. - Runtime access:
el.style.setProperty('--gap','24px')from JavaScript. - Limits: cannot be used for property names, selectors, or inside media-query conditions.
VII. Adaptation and Motion
A. Responsive Web Design
Coined by Ethan Marcotte (2010): one codebase adapting to viewport, built on fluid grids, flexible media and media queries.
- Prerequisite:
<meta name="viewport" content="width=device-width, initial-scale=1">. - Media queries, mobile-first: base styles for small screens, then
@media (min-width: 768px) { … }to add complexity; common breakpoints 576/768/992/1200px. - Flexible media:
img { max-width: 100%; height: auto; };srcsetfor resolution switching. - Query-free fluidity:
clamp()for type scales,minmax()/auto-fitgrids,flex-wrap. - Feature queries:
@media (prefers-reduced-motion: reduce)and@supports (display:grid).
B. CSS Transitions
A transition interpolates a property between two states triggered by a state change.
.btn { background:#06c; transition: background .3s ease-in-out, transform .2s; }
.btn:hover { background:#049; transform: translateY(-2px); }- Longhands:
transition-property,-duration,-timing-function(linear,ease,cubic-bezier(.4,0,.2,1)),-delay. - Requirements: only animatable properties with interpolatable values change smoothly;
display:none→blockcannot transition, andautoheights generally will not.
C. CSS Animations
Animations run a named @keyframes timeline without needing a state change.
@keyframes pulse {
from { opacity: 1; }
50% { opacity: .4; }
to { opacity: 1; }
}
.dot { animation: pulse 1.2s ease-in-out infinite alternate; }- Sub-properties:
animation-name,-duration,-timing-function(includingsteps(4, end)for sprite effects),-delay,-iteration-count(infinite),-direction(alternate,reverse),-fill-mode(forwardskeeps the final frame),-play-state. - Transitions vs animations: transitions are event-driven and two-state; animations are self-starting, multi-keyframe and repeatable.
D. Performance and Limitations of Motion
Animation cost depends on which rendering stage a property touches.
- Cheap (compositor only):
transformandopacity— no layout or paint; prefertransform: translateX()over animatingleft. - Expensive:
width,height,top,marginforce reflow of the layout tree each frame, risking dropped frames below 60 fps. - Hints and accessibility:
will-change: transformpromotes a layer sparingly; always honourprefers-reduced-motionfor vestibular safety.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →