Introduction to CSS
CSS (Cascading Style Sheets) controls how a web page looks: colours, fonts, spacing and layout. HTML says what something is; CSS says how it should appear.
A CSS rule
h1 {
color: #5a48f5;
font-size: 40px;
}h1is the selector: which elements the rule applies to.- Inside the braces are declarations, each a property and a value, ending with a semicolon.
<style>
h1 { color: #5a48f5; font-family: system-ui; }
p { color: #444; line-height: 1.6; max-width: 40ch; }
</style>
<h1>Hello, CSS!</h1>
<p>Change the colours in the style block and press Run. Try red, teal or #ff6b6b.</p>Three ways to add CSS
1. External stylesheet (the best way for real sites): CSS lives in its own file, linked from the head.
<link rel="stylesheet" href="style.css">One stylesheet can style every page of a site, so a change in one place updates everything. The playground's web template is set up this way.
2. Internal stylesheet: a <style> block in the page's head, as in the example above. Handy for single pages and demos.
3. Inline styles: a style attribute on one element.
<p style="color: white; background: #0aa9cf; padding: 8px;">Styled inline.</p>Inline styles are hard to maintain; use them sparingly.
The cascade
When several rules target the same element, CSS decides which wins using the cascade: more specific selectors beat less specific ones, and when specificity is equal, the rule that comes last wins.
<style>
p { color: gray; }
p { color: green; } /* same specificity, later: wins */
.special { color: crimson; } /* a class is more specific than an element */
</style>
<p>Green paragraph</p>
<p class="special">Crimson paragraph</p>Where CSS goes next
Everything here is plain CSS, which every tool below builds on:
| Tool | What it adds |
|---|---|
| variables, nesting and functions, compiled to plain CSS | |
| small utility classes you combine in your HTML | |
| ready-made components and a grid (the Bootstrap course) |