Introduction
A .css file is a style sheet that sets how web pages look: colours, fonts,
spacing and layout. The structure of a page stays in
HTML, which loads the style sheet with a
link element. Håkon Wium Lie proposed CSS in 1994, and the
World Wide Web Consortium published the first
level as a recommendation in 1996. It now grows through separate modules, each with its
own specification.
Tools such as Sass produce .css files from other languages, and
bundlers commonly strip them of spaces and comments for delivery.
Structure
A style sheet is plain text, normally UTF-8. A file in another encoding can name it with
@charset, which must be the very first thing in the file. Comments are
written /* */; there is no line comment.
The file is a list of rules. A rule has a selector, which picks elements, and a block
of declarations in braces, each a property, a colon, a value and a semicolon. At-rules
start with @, such as @media, @import,
@font-face and @keyframes. Custom properties have names
starting with two hyphens and are read with var(). Rules can also be nested
inside other rules.
When several rules set the same property on an element, the cascade decides which wins, by origin and importance, then specificity, then which comes last.
/* Cards use the site's accent colour. */
:root {
--accent: #0b6e4f;
}
.card > h2 {
color: var(--accent);
margin-block: 0 0.5rem;
}
@media (min-width: 40rem) {
.card {
display: grid;
grid-template-columns: 1fr 2fr;
}
}
Links
Software
- Firefox – web browser with style sheet inspection tools (Windows, macOS, Linux)
- Google Chrome – web browser with style sheet inspection tools (Windows, macOS, Linux)
- Visual Studio Code – free code editor with built-in CSS support (Windows, macOS, Linux)
Developers
- PostCSS – parses CSS and transforms it with plugins (JavaScript)
- Lightning CSS – parser, transformer and minifier (Rust)
- CSSTree – CSS parser and tools (JavaScript)
- Sass – language that compiles to CSS (JavaScript)
Reference
- CSS current work – the W3C’s list of every CSS specification and its status
- CSS Syntax Module Level 3 – how a style sheet is tokenised and parsed
- MDN CSS reference – Mozilla’s documentation of properties and selectors