Notice: Due to an ongoing migration of our storage and publishing system, material requested since last month will not be uploaded for the time being, and new requests are paused. All existing notes remain available.

Unit 3 Cascading Style Sheets

CSE326 — Internet Programming 9 min read

Practice MCQs Subjective questions
Text size
100%

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. !important jumps 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, initial and unset force 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; inline style outranks any selector; !important outranks 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 ::.

CSS
blockquote::before { content: "\201C"; font-size: 2rem; }
  • Generated content: ::before / ::after require a content value (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"] (value en or en-…).
  • 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); also radial-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, so 1.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, but padding-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.

Text
total width (content-box) = width + padding-L/R + border-L/R
  • box-sizing: content-box (default) adds padding/border outside width; border-box includes them, so width:200px; padding:20px still occupies 200px. *{box-sizing:border-box} is a standard reset.
  • Margins: shorthand margin: 10px 20px (vertical, horizontal); margin: 0 auto centres 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 shadow box-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|auto controls content larger than the box.

B. Positioning Techniques

position changes which box a element is offset from and whether it stays in normal flow.

  1. In-flow: static (default, offsets ignored) and relative (offset from its own position by top/left, original space preserved; also establishes a containing block).
  2. 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-index applies only to positioned or flex/grid items; higher values paint on top within the same stacking context.
    • Floats: float: left|right removes a box from normal flow horizontally; clear: both or a modern display:flow-root container contains it.

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: 1 means 1 1 0%, so items share space equally; align-self overrides the container; order re-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.

CSS
.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: fr distributes free space; minmax(min,max) bounds a track; auto-fit/auto-fill with repeat() produce responsive column counts without media queries.
  • Placement: by line number (grid-row: 2 / 4), by span, or by name using grid-template-areas with matching grid-area values.
  • 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 all inputs share one tag name.
  • Resetting native chrome: appearance: none for custom checkboxes, selects and range sliders; font: inherit because 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, fieldset and legend for grouping; set box-sizing:border-box so width:100% fields do not overflow.

B. CSS Variables

Custom properties store reusable values in the cascade itself, unlike preprocessor variables resolved at compile time.

CSS
:root { --brand: #0066cc; --gap: 16px; }
.btn { background: var(--brand); padding: var(--gap); }
.dark { --brand: #6ab7ff; }   /* re-theme by scope */
  • Declaration: any property beginning --; usage via var(--name, fallback).
  • Inheritance and scoping: values inherit, so redefining --brand on 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; }; srcset for resolution switching.
  • Query-free fluidity: clamp() for type scales, minmax()/auto-fit grids, 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.

CSS
.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 → block cannot transition, and auto heights generally will not.

C. CSS Animations

Animations run a named @keyframes timeline without needing a state change.

CSS
@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 (including steps(4, end) for sprite effects), -delay, -iteration-count (infinite), -direction (alternate, reverse), -fill-mode (forwards keeps 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): transform and opacity — no layout or paint; prefer transform: translateX() over animating left.
  • Expensive: width, height, top, margin force reflow of the layout tree each frame, risking dropped frames below 60 fps.
  • Hints and accessibility: will-change: transform promotes a layer sparingly; always honour prefers-reduced-motion for vestibular safety.

Test yourself on unit 3

60 MCQs on what you just read, each marked as you answer with an explanation.