Cascading Style Sheets (CSS) control how HTML and XML documents look — colours, fonts, spacing, layout and animation — separately from their content. Selectors, the cascade and specificity, the box model and positioning are the core; XSL is the stylesheet family for XML.
Medium 55 minSyllabus: “Style sheets”
Mark as
The idea in one minute
If HTML is the skeleton of a page, CSS is its clothing. You write the dress code once — 'every heading navy, every notice in a pale box, everything in one column on phones' — and the browser applies it to every page that links the style sheet. When two rules disagree, the cascade settles it, much like office rules where a specific instruction from your own manager beats a general circular, and an order marked 'urgent' (!important) beats both.
Key points — the night-before list
Rule = selector + declaration block: p { color: red; text-align: center; }. Declarations are property: value pairs separated by semicolons. MIME type text/css.
Three ways: inline (style attribute), internal (style element in head), external (link rel="stylesheet"). Textbook precedence: !important > inline > internal > external > browser default.
Specificity: inline 1,0,0,0 · id 0,1,0,0 · class/attribute/pseudo-class 0,0,1,0 · element/pseudo-element 0,0,0,1. Compare left to right; ties go to the later rule.
Box model from inside out: content → padding → border → margin. With box-sizing: content-box (default) the width excludes padding and border; with border-box it includes them.
Vertical margins of adjacent blocks collapse to the larger one (30px + 20px → 30px). Horizontal margins never collapse.
position: static (default) · relative (offset, keeps its space) · absolute (out of flow, relative to nearest positioned ancestor) · fixed (viewport) · sticky. z-index works on positioned elements.
Units: px absolute; em = parent's font size (for font-size); rem = root font size (16px default); % of parent; vw/vh = 1 % of viewport width/height.
XSL family for XML: XSLT (transform), XPath (select), XSL-FO (format for print). CSS can also style XML directly via an xml-stylesheet instruction.
01Why style sheets, and CSS syntax
Early HTML mixed content and looks: font tags, bgcolor attributes and tables for layout on every page. Cascading Style Sheets (CSS) separate the two. HTML says what the content is; CSS says how it should look. One style-sheet file can restyle a whole site, pages become smaller (the CSS is downloaded once and cached), the same content can be styled differently for screen and print, and accessibility improves.
Håkon Wium Lie proposed CSS in 1994, working with Bert Bos at CERN and W3C. CSS1 became a W3C Recommendation in 1996, CSS2 in 1998 and CSS 2.1 in 2011. After that CSS was split into separately versioned modules (Selectors, Backgrounds and Borders, Flexbox, Grid, Animations…); 'CSS3' is a convenient name for that collection, not a single specification.
CSSThe final semicolon before } is optional, but writing it avoids mistakes when lines are added
/* selector declaration block */h1 { color: navy; font-size: 28px; }
/* property: value; — a declaration; semicolons separate them */
p.notice {
background-color: #fff8e1; /* pale yellow */border-left: 4px solid #f9a825;
padding: 8px12px;
text-align: center;
color: red
}
A rule (rule-set) is a selector plus a declaration block in braces.
Each declaration is property: value; declarations are separated by semicolons, never commas.
Comments are written /* … */ — CSS has no // comments.
Property names and keywords are case-insensitive; class and id names are case-sensitive.
A browser silently ignores any declaration it does not understand, so one typo disables only that line.
PSC favourite
Correct syntax: p { text-align: center; color: red; } — colon between property and value, semicolons between declarations, braces around the block. Options with a missing colon, commas between declarations, or round brackets are wrong.
02Three ways to add CSS — and which one wins
HTML
<!-- 1. External: a separate .css file shared by every page --><link rel="stylesheet" href="site.css"><!-- 2. Internal (embedded): a style element inside head, for this page only --><style>
h3 { font-family: Arial, sans-serif; color: red; }
</style><!-- 3. Inline: a style attribute on one element --><h3 style="font-family: Arial; color: blue;">Last date: 31 March</h3><!-- @import pulls one style sheet into another (inside a style element or a .css file) --><style>
@import url("print.css") print;
</style>
Method
Where
Scope
Pros
Cons
External
link element → .css file
Every page that links it
One file restyles the site; cached by the browser
An extra HTTP request
Internal / embedded
style element in head
One page
No extra file; good for page-specific rules
Repeated on every page that needs it
Inline
style attribute
One element
Quick override; highest specificity
Mixes looks with content; hard to maintain
When two declarations set the same property on the same element, the browser runs the cascade: (1) importance — !important declarations beat normal ones; (2) origin — the page author's styles beat the user's, which beat the browser's built-in defaults; (3) specificity of the selector; (4) source order — if everything else ties, the declaration that comes later wins. An inline style attribute has the highest specificity of all, so it beats internal and external rules unless they use !important.
PSC favourite
Textbook order of precedence (asked in 2024): !important > inline > internal > external (> browser default). In a 2024 question, a link to file.css was 'external', a style attribute on h3 was 'inline' and a style block in the head was 'internal'.
Watch out
'Internal beats external' is a simplification: both are author styles, so for equal specificity whichever comes later in the document wins. A link placed after the style block would override it.
Elements with class="note" (an element may have several classes)
ID
#main
The one element with id="main"
Grouping
h1, h2, h3
All three element types — one rule, several selectors
Descendant
div p
p anywhere inside a div, at any depth
Child
ul > li
li elements that are direct children of a ul
Adjacent sibling
h2 + p
The p immediately after an h2 (same parent)
General sibling
h2 ~ p
Every p after an h2 with the same parent
Attribute present / equals
[required], [type="text"]
Elements having the attribute / with exactly that value
Attribute begins / ends / contains
[href^="https"], [href$=".pdf"], [href*="kshb"]
Value starts with / ends with / contains the text
Attribute word / language
[class~="warn"], [lang|="en"]
Space-separated word list contains warn / lang is en or starts with en-
Pseudo-class / pseudo-element
Selects
:link, :visited
Unvisited / visited links
:hover, :active, :focus
Mouse over it / being clicked / has keyboard focus
:first-child, :last-child
An element that is the first / last child of its parent
:nth-child(2n+1), :nth-of-type(2)
Odd children / the second of its element type
:not(.done)
Elements that do not match the inner selector
:checked, :disabled, :invalid
Form-control states
::before, ::after
Generated content inserted before / after the element's content (needs content)
::first-letter, ::first-line
The first letter / first rendered line of a block
::selection, ::placeholder
Text the user has selected / a placeholder's text
:nth-child(an+b) picks children whose position (counting from 1) equals an+b for n = 0, 1, 2, … So 2n+1 (or odd) gives 1, 3, 5, …; 3n gives 3, 6, 9; -n+3 gives 3, 2, 1 — the first three; n+8 gives the 8th onwards. Pseudo-classes describe a state or position of a real element (single colon); pseudo-elements create a part that is not in the HTML (double colon in CSS3 — browsers still accept the old single colon for :before and :after).
CSS
tr:nth-child(even) { background: #f5f5f5; } /* zebra-striped table rows */
a[href$=".pdf"]::after { content: " (PDF)"; } /* label every PDF link */
label.required::after { content: " *"; color: red; }
input:focus:invalid { border-color: crimson; }
p::first-letter { font-size: 200%; float: left; } /* drop cap */
nav a:link, nav a:visited { color: navy; }
nav a:hover { text-decoration: underline; }
nav a:active { color: orange; }
LoVe HAte
Write link states in the order :link → :visited → :hover → :active. All four have equal specificity, so a later rule wins — put :hover before :visited and visited links stop reacting to hover.
04Cascade, specificity and inheritance
Specificity = (a, b, c, d)
a = 1 if the declaration is in an inline style="…" attribute, else 0
b = number of ID selectors (#main)
c = number of class, attribute and pseudo-class (.note [type="text"] :hover)
d = number of element and pseudo-element selectors (p li ::before)
The universal selector, combinators (space > + ~) and :not() itself add nothing.
Compare a, then b, then c, then d — the first difference decides.
Many books write the same idea as 1000 / 100 / 10 / 1 points
Selector
a, b, c, d
style="color: teal" (inline)
1, 0, 0, 0
#nav .item a:hover
0, 1, 2, 1
ul#list li:first-child::before
0, 1, 1, 3
#main p
0, 1, 0, 1
.panel .note.highlight
0, 0, 3, 0
div p.note
0, 0, 1, 2
p.note and a[href$=".pdf"]
0, 0, 1, 1
p
0, 0, 0, 1
*
0, 0, 0, 0
Listed from strongest to weakest
Specificity is not a decimal number: eleven classes (0,0,11,0) still lose to a single ID (0,1,0,0), because the ID column is compared first. When two selectors have identical specificity, the rule that appears later in the style sheets wins.
!important after a value (color: red !important;) lifts that declaration above every normal declaration, whatever its specificity — even inline styles. Between two !important declarations, specificity and order decide again. Use it sparingly; heavy use makes style sheets impossible to override.
Inheritance passes some property values from a parent to its children. Text-related properties inherit: color, font-family, font-size, font-weight, font-style, line-height, text-align, text-indent, letter-spacing, visibility, cursor, list-style. Box and layout properties do not: margin, padding, border, background, width, height, display, position, overflow. The keywords inherit, initial and unset force the behaviour either way.
Watch out
An inherited value has no specificity at all. A rule that targets the element itself — even the universal selector * with specificity 0 — beats any value it would inherit from its parent, however specific the parent's rule was.
05The box model
The browser lays out every element as a rectangular box of four layers, from the inside out: the content area (text, images), padding (space inside the border, which shows the background), the border, and the margin (transparent space outside the border that separates the box from its neighbours).
/* the common reset: make width mean the visible box width everywhere */
*, *::before, *::after { box-sizing: border-box; }
.card {
width: 300px;
padding: 20px; /* all four sides */border: 5px solid #ccc; /* width style colour */margin: 10px auto; /* 10px top and bottom, centred horizontally */
}
Shorthand with 4 values runs clockwise from the top: margin: 10px 20px 30px 40px = top 10, right 20, bottom 30, left 40 (remember TRouBLe: Top Right Bottom Left).
Margin collapsing: when the bottom margin of one block meets the top margin of the next, only the larger survives (30px and 20px give a 30px gap, not 50px). It happens only vertically, between ordinary block boxes — not for floats, absolutely positioned boxes, flex or grid items, or when padding or a border separates the margins.
outline is drawn outside the border but takes no space, so it never shifts the layout.
PSC favourite
The box-model properties are margin, border, padding and the content (width/height). 'Length' is not a box-model property (asked in 2024).
06Layout: display, position, float, flexbox and grid
display
Behaviour
block
New line, full width, width/height/margins all apply (div, p, h1)
inline
Flows in the line; width and height are ignored (span, a, strong)
inline-block
Flows in the line but accepts width, height and vertical margins
none
Removed from the layout entirely — takes no space
flex
Children become flex items laid out along one axis
grid
Children placed in rows and columns of a two-dimensional grid
display: none
Element removed from the layout
Takes no space; neighbours close the gap
Not announced by screen readers
visibility: hidden
Element is invisible
Still takes up its space — an empty hole remains
Children can override with visibility: visible
position
Positioned relative to
Keeps its space in the flow?
static (default)
Normal flow — top/left are ignored
Yes
relative
Its own normal position, nudged by top/right/bottom/left
Yes — the original space stays reserved
absolute
The nearest positioned (non-static) ancestor; otherwise the initial containing block
No — taken out of the flow
fixed
The viewport — stays put when the page scrolls
No
sticky
Acts relative until a scroll threshold (e.g. top: 0), then sticks within its container
Yes
z-index sets the stacking order of positioned elements (and of flex or grid items): a higher value is drawn in front. It has no effect on a position: static box. An element with a z-index forms a stacking context, so its children can never rise above an element that is in front of the parent.
float: left or right pushes a box to one side and lets text wrap around it — the original use was images inside articles. clear: left | right | both makes an element start below earlier floats. A parent that contains only floats collapses to zero height; the classic fixes are a clearfix or display: flow-root on the parent.
CSSFlexbox for one-dimensional rows or columns; Grid for two-dimensional layouts
.toolbar {
display: flex;
flex-direction: row; /* main axis: left → right (column = top → bottom) */justify-content: space-between; /* spacing along the main axis */align-items: center; /* alignment on the cross axis */flex-wrap: wrap; /* allow items to move to a new line */gap: 12px;
}
.toolbar .search { flex: 1; } /* grow to take all the free space */.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr); /* three equal columns */gap: 16px;
}
07Units, colours, fonts and backgrounds
Unit
Meaning
px
CSS pixel — 1/96 inch on paper; the usual absolute unit on screens
pt, cm, mm, in
Physical units, mostly for print (1pt = 1/72 inch)
em
For font-size: the parent's font size. For other properties: the element's own font size
rem
The root (html) element's font size — 16px by default in browsers
%
Percentage of the parent (width of the containing block, parent's font size…)
vw, vh
1 % of the viewport's width / height
vmin, vmax, ch
1 % of the smaller / larger viewport side; width of the digit 0
With the default 16px root: a .card with font-size: 1.25em inside body is 20px; an h2 inside it with 1.5em is 30px; a p with 1rem is 16px wherever it sits. emcompounds when nested — three nested lists at 1.2em each reach 16 × 1.2³ ≈ 27.6px — while rem stays 19.2px at every level. That is why rem is preferred for font sizes and em for spacing that should scale with the local text.
Colour notation
Example
Keyword
red, navy, teal, transparent, currentColor
Hexadecimal
#ff0000, short form #f00 (each digit doubled), with alpha #ff000080
hsl(0, 100%, 50%) — hue in degrees, saturation, lightness
opacity: 0.5 makes the whole element, including its children and text, semi-transparent; an rgba() background makes only that colour transparent and leaves the text solid. Fonts: font-family takes a fallback list ending in a generic family — font-family: "Noto Sans Malayalam", Arial, sans-serif; (generic families: serif, sans-serif, monospace, cursive, fantasy). Also font-size, font-weight (normal = 400, bold = 700), font-style: italic, line-height, text-align, text-decoration, text-transform: uppercase, and @font-face to load a web font.
CSS
body {
background-color: #fafafa;
background-image: url("tile.png"); /* note url(...) */background-repeat: repeat; /* default: tile in both directions */background-position: top left;
background-attachment: fixed; /* stays still while the page scrolls */
}
.hero {
background: url("flats.jpg") no-repeat center / cover; /* shorthand: image, repeat, position / size */
}
.banner {
background-image: linear-gradient(to right, #00796b, #4db6ac);
}
PSC favourite
If a background image is smaller than the page it is repeated (tiled) by default (asked in 2023). The correct syntax is background-image: url("1.gif"); — forms like background-image("1.gif") are invalid.
08Responsive design, CSS3 features and the XSL family
Responsive design makes one page work on phones, tablets and desktops: fluid widths (percentages, fr units, flexbox), flexible images (max-width: 100%), the viewport meta tag, and media queries that apply rules only when conditions hold. Mobile-first style sheets write the phone layout first and add min-width queries for larger screens.
CSSAt 800px both the first rule and the 600px query apply; at 1200px the later 1000px query overrides with four columns
A transition animates a property between two states when it changes (for example on :hover). An animation runs a sequence of @keyframes on its own, any number of times. A transform (translate, rotate, scale, skew) changes how a box is drawn without affecting the layout around it.
For XML, the W3C's style-sheet language is XSL (eXtensible Stylesheet Language), a family of three parts: XSLT transforms XML into HTML, text or other XML; XPath selects the nodes being transformed; and XSL-FO (Formatting Objects) describes paged layout for print, turned into PDF by tools such as Apache FOP. CSS can also style XML elements directly:
Yes — sort, filter, compute totals, generate new markup
Syntax
Its own rule syntax
XML
Output
Styled rendering of the same document
A new document (HTML, XML, text) or paged formatting objects
Typical use
Every web page
Data-to-report conversion, PDF generation
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Who wins? A specificity contest
HTML: <div id="main" class="panel"><p class="note highlight">Last date</p></div>. Rules: (1) p { color: black; } (2) .note { color: green; } (3) div p.note { color: blue; } (4) #main p { color: orange; } (5) .panel .note.highlight { color: purple; }. What colour is the text? What if (6) p.highlight { color: red !important; } is added, and then an inline style="color: teal"?
EX 2Box-model widths and collapsing margins
A .card has width 300px, padding 20px, border 5px and margin 10px on all sides. (a) How wide is it on screen and how much horizontal space does it occupy with the default box-sizing? (b) Repeat with box-sizing: border-box and find the content width. (c) Two such cards are stacked vertically — what is the gap between their borders?
EX 3em vs rem arithmetic
The root font size is the default 16px. Find the computed size of: (a) .card { font-size: 1.25em } placed in body; (b) .card h2 { font-size: 1.5em }; (c) .card p { font-size: 1rem; padding: 1em; } — both values; (d) a list item in a third-level nested list where every li has font-size: 1.2em, versus 1.2rem.
EX 4Which media queries apply?
Using the mobile-first style sheet in the responsive-design section, describe the gallery columns and the sidebar at viewport widths 500px, 800px and 1200px.
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
A list has 10 li items. Which items does each selector match? (a) li:nth-child(3n) (b) li:nth-child(2n+1) (c) li:nth-child(-n+3) (d) li:nth-child(n+8) (e) li:nth-last-child(2)
Q2
Rank these selectors from highest to lowest specificity and give each as (a,b,c,d): .menu li a, #top, nav ul li a, a:hover, #top .menu a, [type="submit"].btn
Q3
A div.box has position: relative. Inside it, a span.tag has position: absolute; top: 0; right: 0;. Where does the tag appear? What changes if you remove position: relative from the box? And what if the tag had position: fixed instead?
Q4
Body has color: navy; border: 2px solid red; padding: 10px; font-family: Georgia; background: #eee; text-align: center;. Which of these values does a p inside the body inherit?
Q5
Write CSS that (a) styles navigation links navy, underlined on hover and orange while being clicked, in the correct order; (b) fades a button's background colour over 0.3 s on hover; (c) hides aside.related on screens narrower than 768px.
Exam traps
Specificity is compared column by column, not added up: 11 classes never beat one ID.
em for font-size refers to the parent's size, but for padding and margins to the element's own font size; rem always refers to the root.
display: none removes the box and its space; visibility: hidden hides it but keeps the space.
Margins collapse only vertically between block boxes (taking the larger), never horizontally and never in flex or grid layouts.
Textbooks say 'internal beats external'; in reality both are author styles and the later one wins for equal specificity. Use the textbook order in MCQs.
opacity fades the whole element including its text and children; an rgba() background fades only the background colour.
Quiz — KPSC style
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.