Bookmarks
ReferenceFrontendVerified

HTML and CSS

HTML and CSS are the languages for marking up and styling web pages. The reference covers: semantics, forms, selectors and the cascade, the box model, Flexbox, Grid and responsive design.

checked 1 Nov · next check 8 Nov · 55 min read

Sections
13
Reading
55 min
Languages
RU · UZ · EN
Written from
developer.mozilla.org/en-US/docs/Web/HTML

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What HTML and CSS are and how they work

HTML is a markup language that describes the structure and meaning of a page’s content: headings, paragraphs, links, forms. CSS is a language of rules that sets how these elements look and where they sit on the screen. The browser reads both and turns them into a picture of the page.

An HTML document is an ordinary text file with the .html extension; a site’s home page is usually called index.html. To see the result, save the file and open it in a browser tab. Even without any CSS of your own the page is readable: the browser has its own default styles (the user agent stylesheet) — headings are larger than body text, links are underlined. What the browser actually received and applied is shown by the developer tools — see the section “Common errors and troubleshooting”.

A minimal document

htmlindex.html
<!doctype html><html lang="ru">  <head>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width">    <title>Class schedule</title>    <link rel="stylesheet" href="styles.css">  </head>  <body>    <h1>Class schedule</h1>    <p>Classes run on Tuesdays and Thursdays.</p>  </body></html>
  • <!doctype html> — the mandatory first line: a historical relic without which the rest may not work correctly.
  • <html> — the root element: everything else sits inside it.
  • <head> — information about the page that the reader does not see: the encoding, the title, the styles.
  • <meta charset="utf-8"> — the UTF-8 encoding: text in most of the world’s languages displays without distortion.
  • <meta name="viewport"> — the width of the page on a phone; more detail in the section “Responsive design”.
  • <title> — the name shown in the browser tab and in bookmarks.
  • <body> — everything visible on the page.

How CSS is written

A stylesheet is a list of rules. A rule starts with a selector that picks out elements; the declaration block follows in curly braces. A declaration is a “property: value” pair, and declarations are separated by semicolons.

cssstyles.css
h1 {  color: #1d3a8a;  font-size: 2.5em;}

Three ways to attach CSS

MethodHow to write itWhen it fits
External file<link rel="stylesheet" href="styles.css"> in <head>the default: one file styles every page of the site
Internal stylesheet<style>…</style> in <head>a single page, or no access to the CSS files
Inline stylethe style="color: purple" attribute on an elementa last resort: the style of a single element is mixed into the markup

Choose an external file: it is attached to every page, and the style changes in one place. Rules from <style> would have to be repeated on each page, and the style attribute on every element.

How the browser builds the page

The browser parses the HTML into a DOM tree and the CSS into a separate CSSOM tree. From them it builds the render tree: only the visible nodes with their computed styles end up in it. The browser then works out the size and position of every box (layout), paints the pixels (paint) and stacks the page’s layers in the right order (composite). When sizes change — for example, an image without set width and height finishes loading — layout and paint run again.

Elements with display: none and the contents of <head> do not get into the render tree, while an element with visibility: hidden does: it takes up space.

How Flexbox differs from Grid

FeatureFlexboxGrid
Dimensionsone: a row or a columntwo: rows and columns at once
Where sizes come fromfrom the content: elements divide the space in their rowfrom the layout: first the grid, then elements placed into its cells
Wrapping to a new roweach row distributes the space on its own, columns do not line upelements stay in strict rows and columns
Typical taska row of items that need to be spaced out evenly inside a containera layout into which items are placed by rows and columns

Choose Flexbox when the layout needs controlling along a row or along a column only, and Grid when it needs controlling along rows and columns at the same time. If in Flexbox you set widths on items so that they line up exactly beneath the items of the row above, what you need is a grid. Both align items with the same properties from the CSS Box Alignment module.

What to know beforehand

  • Working with files and folders: create a file, save it, open it in a browser
  • Page behaviour, the DOM and events — the JavaScript reference
  • How people use a page with a screen reader and from the keyboard — the “Accessibility (a11y)” reference

Section sources

the section is written from these pages

Cheat sheet

Common elements, selectors and everyday layout techniques; each row is explained in its own section of the reference.

Document skeleton

TaskHow to write it
Browser standards mode<!doctype html> as the first line
Character encoding<meta charset="utf-8">
Page width on a phone<meta name="viewport" content="width=device-width">
Title in the browser tab<title>Class schedule</title>
Link a stylesheet<link rel="stylesheet" href="styles.css">

Semantic elements

TaskHow to write it
Site or article header<header>
Main menu<nav>
Main content, one per page<main>
Self-contained block: an article, a post, a card<article>
Thematic section with a heading<section>
Tangentially related content<aside>
Footer<footer>
Illustration with a caption<figure> and <figcaption>
A date for humans and machines<time datetime="2026-10-31">31 October</time>
Important text<strong>

Forms

TaskHow to write it
Field label<label for="email">Email</label> <input id="email" name="email">
Required field<input name="name" required>
Email address with format validation<input type="email" name="email">
Number within a range<input type="number" name="qty" min="1" max="10">
Group of radio buttons<fieldset><legend>Plan</legend>…</fieldset>
Submit button<button type="submit">Submit</button>
A button that does not submit the form<button type="button">
Form with file upload<form method="post" enctype="multipart/form-data">

Selectors

TaskSelector
Elements with a class.card
Descendants at any depth.menu a
Direct children only.menu > li
An element immediately after anotherh2 + p
Field by attributeinput[type="email"]
Hover and visible focusa:hover, a:focus-visible
Every other itemli:nth-child(2n)
All except the last oneli:not(:last-child)
A card that contains an image.card:has(img)
A field the user has filled in incorrectlyinput:user-invalid

Layout

TaskCSS
Width including padding and borderbox-sizing: border-box
Items in a row with a gapdisplay: flex; gap: 1rem;
Wrap onto a new lineflex-wrap: wrap
Centre on both axes in Flexboxdisplay: flex; justify-content: center; align-items: center;
Centre on both axes in Griddisplay: grid; place-items: center;
Push a menu item to the right edgemargin-left: auto on the item
Three equal columnsgrid-template-columns: repeat(3, 1fr)
A card grid without media queriesgrid-template-columns: repeat(auto-fit, minmax(16rem, 1fr))
An element spanning the full grid widthgrid-column: 1 / -1
A header that sticks on scrollposition: sticky; top: 0;

Responsive design and debugging

TaskHow to write it
Styles for wide screens@media (width >= 48rem) { … }
Styles for the system’s dark colour scheme@media (prefers-color-scheme: dark) { … }
Styles based on container widthcontainer-type: inline-size; and @container (width > 30rem) { … }
An image no wider than its columnimg { max-width: 100%; }
Final computed values of propertiesthe “Computed” tab in developer tools
Validate the markupthe W3C Markup Validation Service

Section sources

the section is written from these pages

Semantic markup

A semantic element says what the content is, not what it looks like: <nav> is a menu, <main> is the main part of the page, <h2> is a section heading. From elements like these a screen reader finds the menu and the main content, while the appearance is still set by CSS.

A typical page skeleton: a header <header>, a menu <nav>, one <main> area with the main content, and a footer <footer>. Inside <main> sit articles and sections with their own headings; the <aside> block is often placed there too. When no semantic element fits a block, neutral wrappers are used: the block-level <div> and the inline <span>.

The nav menu can also go inside header: the spec allows a header to contain navigation.

Which element to choose

ElementWhen to use it
headerintroductory part of a page or an article: logo, heading, search
navthe main navigation; a short list of links in the footer does not need nav
mainthe main content of the page; once, directly inside body
articlea self-contained block that makes sense without the rest of the page: an article, a post, a comment, a product card
sectiona thematic part of the document, usually with a heading
asidecontent only indirectly related to the page: a help note, an author bio, related links
footerinformation about the page or the section: author, copyright, related links
div, spanwrappers for styling when no suitable semantic element exists

Headings <h1>–<h6>

<h1>–<h6> are six levels of headings, with <h1> at the top. Choose the level by how deeply the sections are nested, and set the text size in CSS. The HTML standard requires each heading to be no more than one level deeper than the previous one: <h2> follows <h1>, not <h3>. A document should have at least one heading of level 1.

htmlno skipped levels
<h1>Apples</h1><p>Apples are a fruit.</p><section>  <h2>Taste</h2>  <p>Sweet and crunchy.</p></section>

The meaning of text

ElementWhat it means
pa paragraph
ul, ol, libulleted and numbered lists, a list item
a hrefa link to a page, a file, an email address or a place in the page
strongimportance, seriousness or urgency
ememphasis
bdrawing attention without particular importance; for bold type there is the CSS property font-weight
itext set off for another reason: terms, species names
figure, figcaptiona self-contained illustration or example with a caption
time datetimea date or a time in machine-readable form
blockquotea long quotation
codea fragment of code

Tables for data

<table> is for tabular data: facts arranged in rows and columns. The table caption is <caption>, the header rows go in <thead>, and a header cell is <th>; the scope and headers attributes say which cells a header belongs to.

htmlindex.html
<table>  <caption>Tariffs</caption>  <thead>    <tr>      <th scope="col">Tariff</th>      <th scope="col">Price per month</th>    </tr>  </thead>  <tbody>    <tr><td>Basic</td><td>50,000 UZS</td></tr>    <tr><td>Pro</td><td>120,000 UZS</td></tr>  </tbody></table>

What can be nested

Every element has a content model — what is allowed inside it. A <p> accepts phrasing content only: text and inline elements such as <a>, <strong>, <code>. An <a> cannot contain another link or interactive content: buttons, input fields.

The browser does not report such mistakes. A <p> closes on its own as soon as the parser meets a block-level element — <div>, <ul>, <table> or the next <p> — and the DOM ends up with a different structure than the code has.

htmldon’t do this
<p>Address:  <div>1 Navoi street, Tashkent</div></p>
htmldo this instead
<div>  <p>Address:</p>  <p>1 Navoi street, Tashkent</p></div>

Example: the skeleton of an article page

htmlindex.html
<body>  <header>    <a href="/">Blog</a>  </header>  <nav>    <ul>      <li><a href="/">Home</a></li>      <li><a href="/articles">Articles</a></li>    </ul>  </nav>  <main>    <article>      <h1>How CSS Grid works</h1>      <p>Published <time datetime="2026-10-31">31 October</time></p>      <section>        <h2>Lines and tracks</h2>        <p>Lines make up the grid…</p>      </section>    </article>    <aside>      <h2>Related</h2>      <ul>        <li><a href="/articles/flexbox">Flexbox</a></li>      </ul>    </aside>  </main>  <footer>    <p>© 2026 Blog</p>  </footer></body>

Element roles for screen readers and ARIA attributes are covered in the “Accessibility (a11y)” reference, the section “Semantics for assistive technologies”.

Section sources

the section is written from these pages

Forms and input fields

A <form> gathers the field values into “name=value” pairs and sends them to the address in action with the method in method. A value is only sent if the field has a name attribute. Built-in validation (required, type="email", min) works without JavaScript but does not replace validation on the server.

htmlsignup.html
<form action="/signup" method="post">  <label for="email">Email</label>  <input id="email" name="email" type="email"         autocomplete="email" required>   <label for="age">Age</label>  <input id="age" name="age" type="number" min="16" max="99">   <fieldset>    <legend>Plan</legend>    <input type="radio" id="plan-basic" name="plan"           value="basic" checked>    <label for="plan-basic">Basic</label>    <input type="radio" id="plan-pro" name="plan" value="pro">    <label for="plan-pro">Pro</label>  </fieldset>   <button type="submit">Sign up</button></form>

On submission the browser will pass on the pairs email=…, age=… and plan=basic. Of radio buttons sharing one name only one can be checked, and its value is the one that gets sent. An unchecked checkbox does not appear in the data at all, while a checked one without a value attribute sends on.

GET or POST

MethodWhere the data goesWhen to choose it
getin the address after ?: /search?q=grida form with no side effects: search, filters
postin the request body; the address stays the samepasswords and personal data, large volumes, file uploads

Sent with GET, a password would end up in the address bar, so it is only ever sent with POST. Files go with the POST method, enctype="multipart/form-data" and an <input type="file"> field. What the HTTP methods are for is covered in the “HTTP and REST” reference, section “HTTP methods”.

htmlupload.html
<form action="/upload" method="post"      enctype="multipart/form-data">  <label for="photo">Photo</label>  <input id="photo" name="photo" type="file" accept="image/*">  <button type="submit">Upload</button></form>

Labels and groups

Link each label to its field: <label for> points at the field’s id. A screen reader reads the label together with the field. Clicking the label moves focus to the field or toggles the checkbox, while checkboxes and radio buttons themselves have a very small click area. You can also nest the field inside the <label>, but it is still worth setting for: that way every assistive technology understands the link.

Wrap a group of radio buttons in a <fieldset> with a <legend>: the screen reader will announce the legend before the label of each option. Never nest a form inside another form.

Input types

TypeWhat it is forWhat it gives you on a phone
textsingle-line text; the default typeregular keyboard
emailemail address with format validationemail keyboard
telphone numbertelephone keypad
urlwebsite address with format validationURL keyboard
numbera number; constrained by min, max, stepnumeric keypad on some devices
datea date without a timedate picker
searchsearch boxsearch icon instead of Enter on some devices
passwordpassword, characters hidden—
checkboxcheckbox: checked or not—
radioone option from a group sharing a name—
filefile picker; accept restricts the typesfile picker, camera via capture
hiddenvalue sent to the server, field not visible—

inputmode hints at which on-screen keyboard to show: numeric, decimal, tel, email and others. autocomplete tells the browser which saved data to fill the field with, for example an email address.

Lists and multi-line text

A drop-down list is a <select> with <option> entries; multi-line text is a <textarea>. A <datalist>, linked to the field by the list attribute, offers suggestions: the user picks one of the options or types their own.

htmlcontact.html
<label for="city">City</label><input id="city" name="city" list="cities"><datalist id="cities">  <option value="Tashkent"></option>  <option value="Samarkand"></option></datalist> <label for="plan">Plan</label><select id="plan" name="plan">  <option value="basic">Basic</option>  <option value="pro">Pro</option></select> <label for="msg">Message</label><textarea id="msg" name="msg" maxlength="500"></textarea>

Buttons

For a <button> associated with a form the default type is submit: such a button submits the form. Give a button that does something on the page — shows the password, opens a hint — type="button". type="reset" restores the initial values of the fields; users usually find this annoying.

htmlform.html
<button type="submit">Save</button><button type="button">Show password</button>

Built-in validation

AttributeWhat it validates
requiredthe field is not empty; in a group of radio buttons at least one is checked
minlength, maxlengththe length of the text in input and textarea
min, maxthe range of a number or date
stepthe value step; for number it is 1 by default, so 4.2 would be an error
patterna regular expression for the whole value; textarea has no such attribute
typethe format of the value for email and url

An invalid field matches the pseudo-class :invalid, a valid one — :valid. :user-invalid only applies once the user has interacted with the field, so with it an empty form does not turn red the moment it opens. On submission the browser will not send a form with an invalid field and shows a message instead.

cssstyles.css
input:user-invalid {  border-color: #b3261e;}

The novalidate attribute on a form switches off automatic validation on submission: the browser shows none of its messages and sends the form as is. Your script then does the validation and the messages, while the :valid and :invalid pseudo-classes keep working.

A field with disabled receives no clicks and is not sent with the form; readonly merely forbids changing the value.

Section sources

the section is written from these pages

Selectors

A selector is a pattern a CSS rule uses to pick elements: by tag name, class, attribute, state or position in the document tree. Combinators join selectors by how the elements are related: descendant, direct child, sibling.

cssstyles.css
/* links inside a menu the pointer is over */.menu a:hover {  text-decoration: underline;}

Simple selectors

SelectorWhat it selectsExample
typeall elements with that namep, input
classelements with that value in class.card
idthe element with that id; there must be only one in a document#toc
universalall elements*
attributean attribute’s presence or its value[type], [type="submit"]
compoundall conditions on one element, type firstp.note, input[type="checkbox"]:checked

The selector matches the values of class, id and data-* attributes case-sensitively, and the values of enumerated HTML attributes such as type case-insensitively.

Combinators

CombinatorWritten asWhat it selects
descendant (a space)nav aa at any depth inside nav
childul > lidirect children only
adjacent siblingh2 + pp right after h2, under the same parent
general siblingh2 ~ pall p after h2, under the same parent

Pseudo-classes

A pseudo-class selects an element by information absent from the markup: pointer hover, a checked checkbox, the position among siblings. It is written with a colon, and several pseudo-classes can be combined in one selector: input:required:invalid.

Pseudo-classWhen it matches
:hoverthe pointer is over the element
:focus-visiblethe element has focus and the browser decides the focus should be shown
:checkeda checkbox or radio button is checked
:disabledthe form control is disabled
:first-child, :last-childthe first or the last among its siblings
:nth-child(2n)the position by the An+B formula: here every second one; :nth-child(3) — the third
:not(.active)the element does not match the argument
:is(h1, h2, h3)matches any selector in the list
:where(h1, h2, h3)the same, but with no weight in specificity
:has(img)the element contains something matching the argument
cssstyles.css
.menu a:focus-visible {  outline: 2px solid #0b57d0;} /* stripes in a long list */li:nth-child(2n) {  background: #f4f5f7;}

Selecting the parent with :has()

:has() selects an element by what lies inside it or comes after it — this is how CSS selects a parent or a preceding sibling. All major browsers have supported :has() since December 2023.

cssstyles.css
/* a card that contains an image */.card:has(img) {  display: grid;  grid-template-columns: 8rem 1fr;} /* a heading immediately followed by a paragraph */h2:has(+ p) {  margin-bottom: 0.25rem;}

One :has() cannot be nested inside another, and pseudo-elements do not work inside it. Anchor it to a specific container rather than to body or *: after every DOM change the browser rechecks the condition across the whole subtree.

Pseudo-elements

A pseudo-element selects something that has no element of its own in HTML and is written with two colons: ::marker — a list item’s marker, p::first-line — the first line of a paragraph. ::before and ::after insert content at the start and at the end of an element. Without the content property they never appear, and they do not apply to <img> or other replaced elements.

cssstyles.css
.external::after {  content: " ↗";} li::marker {  color: #0b57d0;}

Do not add meaningful text via ::before: screen readers read such content unreliably.

Selector lists

Comma-separated selectors give one rule for several patterns. If the browser fails to understand even one selector in the list — :has() in an old version, for instance — it discards the entire block. :is() and :where() take a forgiving selector list: an unrecognised option selects nothing and the rest keep working.

cssthe risky way
/* an old browser discards the whole rule */.card:hover,.card:has(:focus-visible) {  border-color: #0b57d0;}
cssthe safer way
/* an unrecognised option is skipped, the rest work */.card:is(:hover, :has(:focus-visible)) {  border-color: #0b57d0;}

Nesting

Rules can be nested inside one another directly in CSS: nesting is parsed by the browser itself, so no preprocessor such as Sass is needed. The & selector stands for the parent rule; it is required when a class or pseudo-class must be attached to the parent: &:hover, &.active.

cssstyles.css
.card {  padding: 1rem;   & h2 {    margin-top: 0;  }   &:hover {    box-shadow: 0 2px 8px rgb(0 0 0 / 0.15);  }}

The specificity of a nested rule is calculated the same way as for :is(). How the browser chooses between rules is covered in the section “Cascade, specificity and inheritance”; finding elements from JavaScript — in the JavaScript reference, section “DOM: finding and changing elements”.

Section sources

the section is written from these pages

Cascade, specificity and inheritance

The cascade — an algorithm that picks a single value for each property out of all the declarations that match an element. Declarations are compared step by step: origin and !important, the style attribute, layers, specificity, order in the code; a later step only comes into play when the previous one is a tie.

A rule wins property by property, not as a whole: an element may get color from one rule and font-size from another. The steps are checked strictly in order, so the site’s styles beat the browser’s styles at any specificity, and unlayered styles beat styles in a layer.

One more step sits between specificity and order — the closeness of the @scope scope, if you use it.
  1. Matching: the declarations whose selector matches the element and whose @media condition holds are kept in.
  2. Origin and importance: for normal declarations the site’s styles beat the user’s and the browser’s, while among !important declarations the order is reversed — an important browser style beats an important site style.
  3. The style attribute: inline styles beat normal site styles from stylesheets.
  4. The @layer layer: unlayered styles beat styles in layers, and among layers the later-declared one wins; for !important declarations the layer order is reversed.
  5. Specificity: the more specific selector wins.
  6. Order in the code: with everything else equal, the declaration that comes last wins.

Specificity

Specificity — a selector’s weight made of three counters: ID, CLASS and TYPE, written as 1-2-1. The counters are compared left to right: one id beats any number of classes, a class beats any number of types. The universal selector * and combinators add no weight.

SelectorSpecificityWhy
p0-0-1one type
.card p0-1-1a class and a type
#main .card p1-1-1an id, a class and a type
a:hover0-1-1a pseudo-class counts as a class
[type="email"]0-1-0an attribute counts as a class
p::first-line0-0-2a pseudo-element counts as a type
:where(#main) p0-0-1:where() always yields zero
:is(#main, .card) p1-0-1:is() takes the weight of its most specific argument

:is(), :not() and :has() add no weight of their own: the weight comes from the most specific selector inside their brackets. An inline style in the style attribute beats any selector; only !important can override it.

Example: why the button is green

cssstyles.css
/* 0-2-0 */.card .btn {  background: green;} /* 0-1-0: comes later, but is weaker */.btn {  background: blue;}

Both rules come from the same stylesheet and sit outside layers, so specificity decides: 0-2-0 against 0-1-0, and the order in the code no longer matters. To let .btn win, lower the weight of the first rule with :where(.card) .btn or arrange your styles into layers. How to see the winner in the developer tools — in the section “Common errors and troubleshooting”.

Cascade layers

@layer groups rules into cascade layers. The order is declared in a single line at the top of the file: a layer declared later wins, and unlayered styles beat any layer whatever the specificity. Put style resets and third-party libraries into an early layer, and your own rules will beat them without raising specificity. For !important the order is reversed: an important declaration from an earlier layer wins. @layer has worked in all major browsers since March 2022.

cssstyles.css
@layer vendor, base, components;@import "vendor.css" layer(vendor); @layer base {  a { color: #0b57d0; }} @layer components {  .btn { padding: 0.5rem 1rem; }} /* unlayered: beats every layer */.btn { padding: 0.75rem 1.25rem; }

Inheritance

Inheritance decides what happens to a property that has no value set. Inherited properties take the value from the parent, the rest get the initial value. Mostly text properties are inherited: color, font-family. width, margin, padding and border are not — otherwise the border would show up on every nested element. Whether a property is inherited is stated in its formal definition (the Inherited line).

A value set on an element directly always beats an inherited one, even if the rule on the parent is more specific.

ValueWhat it does
inherittake the parent’s value
initialthe property’s initial value
unsetfor an inherited property — like inherit, for the rest — like initial
revertrestore the browser’s default style
revert-layerrestore the value from the previous cascade layer

Custom properties

A custom property (a “CSS variable”) — a value named with -- that the var() function substitutes. It takes part in the cascade and is inherited, so it is usually set on :root and redefined further down the tree or inside @media. The second argument of var() — a fallback for when the property is not set.

cssstyles.css
:root {  --brand: #0b57d0;  --gap: 1rem;} @media (prefers-color-scheme: dark) {  :root {    --brand: #8ab4f8;  }} .btn {  background: var(--brand);  padding: var(--gap, 0.5rem);}

Names are case-sensitive: --brand and --Brand — different properties. var() only works in values: it cannot be used in a media query condition, in a selector or in a property name. If the substituted value does not fit the property, the declaration is not discarded as an ordinary error would be: the property gets the inherited or the initial value.

Section sources

the section is written from these pages

The box model and sizing

The box model describes every element as a rectangle made of four areas: the content, the padding, the border and the margin. By default, width sets only the width of the content, so padding and border make the box wider; box-sizing: border-box includes them in width.

The visible box ends at the border: the margin is empty space around it that pushes neighbours away and is not part of the box’s size. The background is painted under the content and the padding. In the standard model (content-box), a box with width: 200px, padding: 20px and border: 2px solid takes up 244 px; in the alternative one (border-box) it is exactly 200 px, leaving 156 px for the content.

Dashes mark the outer edge of the margin: the margin is not part of the box width in either model.
cssstyles.css
/* the width includes padding and border */html {  box-sizing: border-box;} *,*::before,*::after {  box-sizing: inherit;}

box-sizing is not inherited, so the value is set on html, and the other elements are given inherit. <table>, <select>, <button> and some form fields have border-box by default.

Block and inline elements

Behaviourblockinlineinline-block
Starts on a new lineyesnono
width and heightworkhave no effectwork
Vertical marginpush neighbours awayhave no effectpush neighbours away
Vertical padding and borderpush neighbours awayare painted but don’t move neighbours and may overlap thempush neighbours away
Default forp, h1a, span, em, strong—

display changes how an element behaves without changing what it means. A common recipe is enlarging a link’s hit area: on an inline link a vertical padding overlaps the neighbouring lines, while with inline-block it pushes them apart.

cssstyles.css
.links a {  display: inline-block;  padding: 0.5rem 1rem;}

Margin collapsing

The vertical margins of adjacent blocks don’t add up but collapse (margin collapsing) into a single one the size of the larger: margin-bottom: 50px and margin-top: 30px give 50 px. A negative margin is subtracted from the positive one. Horizontal margins never collapse.

margin-top of the first child collapses with the parent’s margin and sticks out beyond its top edge if the parent has no border-top, no padding-top and no text before the child. Floated and absolutely positioned elements never collapse, nor do elements inside flex and grid containers.

cssstyles.css
.card {  /* padding keeps the heading’s margin apart from the .card margin */  padding: 1rem;} .card h2 {  margin-top: 1.5rem;}

Units of size

UnitRelative to
pxan absolute unit, 1/96 of an inch; on high-density screens it is several physical pixels
%the parent’s values: for width — its width, for font-size — its font size
emthe element’s own font size, and in font-size — the parent’s font size
remthe font size of the root html element
vw, vh1% of the viewport width and height

Set fonts and spacing in rem: sizes depend on a single root font size and don’t grow with nesting the way em does. Change font-size on html, and everything set in rem changes proportionally.

Overflow: overflow

When content doesn’t fit into a box with fixed dimensions, CSS doesn’t hide it by default: overflow: visible shows the part that sticks out, so the problem stays visible. The other values clip or scroll it.

ValueWhat happens
visibledefault: the content sticks out beyond the box
clipclips; there is no way at all to scroll to the hidden content
hiddenclips, but the box remains scrollable: from a script or by moving focus into it
autoscrollbars appear only when the content doesn’t fit
scrollscrollbars are always visible

To clip content without scrolling, use clip; hidden is only for cases where the box must remain scrollable. The axes are set separately: overflow-x and overflow-y.

Section sources

the section is written from these pages

Positioning and z-index

The position property shifts an element or takes it out of the normal flow: relative — relative to its own place, absolute — relative to a positioned ancestor, fixed — relative to the viewport, sticky — sticks while scrolling. Which of two overlapping elements ends up on top is decided by z-index and the stacking context.

ValuePositioned relative toPlace in the flow
staticthe normal flow; top, left and z-index have no effecttakes up space (by default)
relativeits usual positiontakes up space, neighbours do not move
absolutethe nearest ancestor with a position other than static; if there is none — the initial containing block, the size of the viewporttakes up no space
fixedthe viewport, unless an ancestor has transform, filter or perspectivetakes up no space
stickylike relative until scrolling brings it to a threshold, then it stickstakes up space
cssstyles.css
.card {  position: relative;} /* badge in the top-right corner of the card */.card .badge {  position: absolute;  top: 0.5rem;  right: 0.5rem;}

position: relative on the card makes it the containing block for the badge. Without it, top and right would be measured from the nearest other positioned ancestor, or from the initial containing block if there is none. An absolutely positioned element is offset from the padding edge of its containing block, and margin collapsing does not apply to its margin.

The containing block

Percentages in width, left, right, padding and margin of an absolutely positioned element are calculated from the width of the containing block, and those in height, top and bottom — from its height. For absolute and fixed, an ancestor with transform, filter or will-change: transform also becomes the containing block: a fixed element is then positioned relative to that ancestor rather than the viewport.

A header that sticks

cssstyles.css
.site-header {  position: sticky;  top: 0;  z-index: 10;}

sticky works only when a threshold is set: top, bottom or another offset; without one the element behaves as relative. The element sticks to the nearest ancestor with a scrolling mechanism — one whose overflow is hidden, scroll or auto — even if that ancestor never actually scrolls. That is why overflow: hidden on a wrapper breaks a sticky header. A stuck element never leaves its containing block.

A layer above the page

cssstyles.css
.overlay {  position: fixed;  top: 0;  right: 0;  bottom: 0;  left: 0;  z-index: 100;  background: rgb(0 0 0 / 0.5);}

Setting top and bottom, left and right at the same time stretches the element over the whole containing block — the viewport here. Focus and keyboard interaction in a modal, the dialog element — in the “Accessibility (a11y)” reference, section “Keyboard and focus”.

z-index and the stacking context

Without z-index, positioned elements are painted above non-positioned ones, and among positioned elements the one later in the code is on top. z-index changes this order for positioned elements and for children of flex and grid containers. The value is an integer with no units; only the order matters: 2 and 3 work just like 300 and 40 000.

A stacking context is a group whose elements are ordered by z-index independently of the rest of the page, while from the outside the whole group acts as a single layer. That is why z-index: 9999 on an element inside a context with z-index: 1 will not lift it above a neighbour from a context with z-index: 2. A stacking context is created by:

  • The root element html
  • position: absolute or relative with a z-index other than auto
  • position: fixed and sticky — always
  • A child of a flex or grid container with a z-index other than auto
  • opacity below 1
  • transform, filter, backdrop-filter and a number of other properties with a value other than none
  • isolation: isolate
  • container-type: size or inline-size
cssstyles.css
/* a stacking context of its own, without position and z-index */.card {  isolation: isolate;}

isolation: isolate creates a stacking context and changes nothing else: the z-index of elements inside the card no longer competes with the rest of the page.

Section sources

the section is written from these pages

Flexbox

Flexbox is a one-dimensional layout: items line up in a row or a column and share the free space between them. A container with display: flex controls only its direct children, and all alignment properties are measured from two axes — the main axis and the cross axis.

The main axis is set by flex-direction: with row it runs along the row, with column it runs top to bottom. The cross axis is perpendicular to the main axis. justify-content distributes items along the main axis, align-items aligns them along the cross axis. Where the axes begin depends on the writing direction: in Arabic text row runs right to left.

This is how the axes run with flex-direction: row and left-to-right writing; with column they swap places.

By default items stand in a single line from the start of the main axis, do not grow, can shrink and stretch to the height of the container: align-items: stretch. When there is not enough room and they cannot shrink any further, they spill over the edge: flex-wrap: wrap turns on wrapping.

cssstyles.css
.toolbar {  display: flex;  flex-wrap: wrap;  gap: 0.5rem 1rem;  justify-content: space-between;  align-items: center;}

Alignment

PropertyAxis and what it applies toCommon values
justify-contentmain, all itemsflex-start, center, flex-end, space-between, space-around, space-evenly
align-itemscross, all itemsstretch (the default), flex-start, center, flex-end, baseline
align-selfcross, one itemthe same, plus auto
align-contentcross, between lines with flex-wrap: wrapas for justify-content, plus stretch
gapgaps between items and lines1rem, 0.5rem 1rem

space-between divides the free space between items, space-around gives each item a half gap at the edges, space-evenly gives equal gaps everywhere, including the edges. justify-items has no effect in Flexbox. That is why the place-items shorthand, which sets align-items and justify-items at once, works here only as align-items; in grid both take effect, and display: grid; place-items: center puts an item in the centre.

How the free space is divided

Three properties set the size of an item along the main axis: flex-basis — the initial size, flex-grow — the share of free space it takes when growing, flex-shrink — how willingly the item shrinks when space runs short. Usually they are written as one flex property, in this order.

ShorthandEqual toWhat it does
flex: initial0 1 autodefault: sized to content, may shrink
flex: auto1 1 autogrows and shrinks from the content size
flex: none0 0 autothe size does not change
flex: 11 1 0items share all the space equally

Three items of 100 px in a 500 px container leave 200 px of free space. With flex-grow: 1 on all of them each gets a third; if the first one has flex-grow: 2, it gets 100 px and the others 50 px each.

Why an item does not shrink

By default a flex item never becomes narrower than its minimum content — its longest word or an element of fixed width: its initial min-width value is auto. A long link or a table inside stretches the line and spills over the container. Allow shrinking explicitly: min-width: 0, and in a column — min-height: 0. For a scrollable block the minimum is already zero.

cssstyles.css
.item {  flex: 1;  /* shrink below the longest word */  min-width: 0;}

order changes only the look

order and the row-reverse, column-reverse values rearrange items on screen, but a screen reader and Tab navigation follow the order of the markup. The Flexbox standard allows order only for visual rearrangement: if the meaningful order changes, change the markup.

Recipes

cssstyles.css
/* centre on both axes */.center {  display: flex;  justify-content: center;  align-items: center;  min-height: 12rem;}
cssstyles.css
/* logo and menu on the left, sign-in on the right */.header {  display: flex;  align-items: center;  gap: 1rem;} .header .login {  margin-left: auto;}

margin-left: auto takes all the free space to the left of the item and pushes it, together with everything that follows, against the right edge.

cssstyles.css
/* cards that wrap, no narrower than 15rem */.cards {  display: flex;  flex-wrap: wrap;  gap: 1rem;} .cards > * {  flex: 1 1 15rem;}

When wrapping, each line distributes the space on its own: cards of the last line stretch across its full width and do not line up under the columns above. If you need even columns, that is a job for grid.

Section sources

the section is written from these pages

Grid

Grid is a two-dimensional layout: a container with display: grid is split into rows and columns. Direct children take up its cells in order, by line numbers or by area names. Columns are set by grid-template-columns, rows by grid-template-rows.

A grid is made up of grid lines. The gap between two neighbouring lines is a track: a row or a column. The intersection of a row and a column is a cell; a rectangle of several cells is an area. Lines are numbered from 1 in the writing direction and from −1 counting from the end, so a grid with three columns has four vertical lines.

A track is any row or column; the diagram highlights the third column.
cssstyles.css
.layout {  display: grid;  grid-template-columns: repeat(3, 1fr);  gap: 1rem;} .hero {  grid-column: 1 / 3;}

fr is a share of the container’s free space: 2fr 1fr 1fr divides it into four parts and gives two to the first track. Fixed tracks and fr can be mixed: pixels are subtracted first. repeat(3, 1fr) is the same as 1fr 1fr 1fr; minmax(100px, auto) is a track at least 100 px wide that grows with its content.

Line-based placement

cssstyles.css
/* across the full width of the explicit grid */.banner {  grid-column: 1 / -1;} /* from the first horizontal line, two tracks down */.sidebar {  grid-row: 1 / span 2;}

grid-column: 1 / 3 means from line 1 to line 3, that is, two columns; if the end line is omitted, the element takes up one track. span 2 means “two tracks” from the starting line. Negative numbers count only within the explicit grid — the one set by grid-template-columns and grid-template-rows — and not in the tracks the grid adds on its own.

Named areas

cssstyles.css
.page {  display: grid;  gap: 1rem;  grid-template-areas:    "header"    "main"    "sidebar"    "footer";} @media (width >= 48rem) {  .page {    grid-template-columns: 16rem 1fr;    grid-template-areas:      "header  header"      "sidebar main"      "footer  footer";  }} .page > header { grid-area: header; }.page > aside { grid-area: sidebar; }.page > main { grid-area: main; }.page > footer { grid-area: footer; }

grid-template-areas draws the layout directly in CSS: area names are set with grid-area, repeating a name stretches the area, and a dot . leaves a cell empty. All rows of the template must have the same number of cells and areas must be rectangular, otherwise the property is ignored. Define area names outside media queries; inside media queries change only the template.

Auto-placement

Elements without an explicit place fill one cell at a time, row by row, in markup order. When the rows run out, the grid adds implicit rows; their height is set by grid-auto-rows. grid-auto-flow: column fills the grid by columns, and dense packs items into the holes left behind. The Tab order still follows the markup order.

cssstyles.css
.gallery {  display: grid;  grid-template-columns: repeat(4, 1fr);  grid-auto-rows: minmax(10rem, auto);  grid-auto-flow: dense;} .gallery .wide {  grid-column: span 2;}

Responsive grid without media queries

cssstyles.css
.cards {  display: grid;  grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));  gap: 1rem;}

auto-fill creates as many columns as fit into the container, while auto-fit collapses empty columns after placement, so the cards stretch to the full width. The difference shows when there are fewer cards than columns that fit: with auto-fill, empty tracks remain on the right.

Gaps and alignment

gap (or row-gap and column-gap) sets the gaps between tracks. The space they take is subtracted before the fr split, and an element cannot be placed into a gap. By default an element stretches across its whole area; justify-items and justify-self align it along the inline axis, align-items and align-self along the block axis.

Subgrid: subgrid

By default a nested grid is not tied to its parent: it has its own tracks and its own lines. The subgrid value takes the parent’s tracks instead of a track list, so the content of neighbouring cards lines up along shared lines: headings at the same height, buttons on the same line.

cssstyles.css
.cards {  display: grid;  grid-template-columns: repeat(3, 1fr);  gap: 1rem;} /* heading, text and button — on the parent’s rows */.card {  display: grid;  grid-row: span 3;  grid-template-rows: subgrid;}

Section sources

the section is written from these pages

Responsive design

Responsive design is an approach in which a single page works well at any screen width. The layout is flexible, images never grow wider than their column, and media queries change the styles where the content starts to feel cramped. It begins with the <meta name="viewport"> line in <head>.

htmlin <head>
<meta name="viewport" content="width=device-width">

Without this line, a mobile browser renders the page in a virtual window roughly 980 px wide and then scales it down to fit the screen. The text comes out small, and media queries for narrow screens never fire. width=device-width makes the window as wide as the screen. initial-scale=1 is usually unnecessary: add it if a page whose content spills over the edge opens up scaled down.

Narrow screen first

The approach is mobile first: write the base styles for a narrow screen — usually a single column — and add columns with media queries once there is enough room. Place breakpoints where the content starts to break, and set them in relative units (em, rem) rather than at the widths of specific phones.

cssstyles.css
.layout {  display: grid;  gap: 1rem;} @media (width >= 48rem) {  .layout {    grid-template-columns: 2fr 1fr;  }}

Media queries

QueryWhen it applies
(width >= 48rem)viewport width is at least 48rem
(30em <= width <= 50em)width is within the range, bounds included
(width < 40em)width is strictly less than 40em
(min-width: 48rem)same condition as (width >= 48rem), in the min- prefixed form
(orientation: portrait)viewport height is greater than width
(hover: hover)the primary input device can hover
(prefers-color-scheme: dark)the user has chosen a dark theme
(prefers-reduced-motion: reduce)the user asks for less motion on screen
printthe page is being printed

Conditions are combined with and, or and not, and queries separated by commas act as “or”. A media query is not mandatory: flexible grids, fr and size constraints often get by without one.

cssstyles.css
.banner {  transition: transform 0.3s;} @media (prefers-reduced-motion: reduce) {  .banner {    transition: none;  }}

Flexible sizes and fonts

Set widths in %, fr and rem: a fixed pixel width brings horizontal scrolling on a narrow screen and empty space on a wide one. A font size set in vw alone won’t do — such text isn’t enlarged by browser zoom; add vw to rem via calc().

cssstyles.css
h1 {  font-size: calc(1.5rem + 4vw);}

Container queries

A container query changes a component’s styles based on the size of its container rather than the screen. That way the same card looks different in a narrow sidebar column and in a wide main one. The container declares container-type: inline-size, conditions go inside @container, and the query looks at the nearest ancestor container.

cssstyles.css
.card-slot {  container-type: inline-size;} .card {  display: grid;  gap: 0.5rem;} @container (width > 30rem) {  .card {    grid-template-columns: 10rem 1fr;  }}

A container can be given a name — container-name: sidebar or, in the short form, container: sidebar / inline-size — and then targeted with @container sidebar (width > 30rem). The cqi and cqw units equal 1% of the container’s inline size and width respectively.

Images

cssstyles.css
img,picture,video {  max-width: 100%;}

max-width: 100% keeps an image from growing wider than its column and doesn’t stretch a small one beyond its natural size. So that a phone doesn’t download the file meant for a large screen, let the browser choose. srcset lists the files and their real width in w units, while sizes says how wide the image will be under each condition.

htmlindex.html
<img  srcset="hall-480w.jpg 480w, hall-960w.jpg 960w"  sizes="(width <= 600px) 480px, 960px"  src="hall-960w.jpg"  alt="Coworking hall with long tables">

The browser takes the first matching condition in sizes and downloads the appropriate file; a browser without support falls back to src. If an image is always the same size and the screens differ in density, srcset with 1.5x and 2x descriptors is enough, without sizes. Different cropping for narrow and wide screens is the job of <picture>; the <img> inside is required — without it there is no image at all.

htmlindex.html
<picture>  <source media="(width < 800px)" srcset="team-portrait.jpg">  <img src="team-wide.jpg" alt="Team at the office entrance"></picture>

Image formats, compression and lazy loading are covered in the “Web performance” reference, in the section “Images and video”.

Check

Resize the window and look for where the content breaks. A desktop browser won’t let you make the window narrower than its own minimum, so check narrow screens on a phone as well. A page opened on it can be inspected with the developer tools on a computer; in Firefox, via the about:debugging page.

Section sources

the section is written from these pages

Common errors and troubleshooting

The browser does not report CSS errors and silently repairs invalid HTML: a rule with an error is discarded and the markup is rebuilt. That is why diagnosis relies on the developer tools (DevTools) and the W3C validators rather than on error messages.

The tools open with F12 or Ctrl+Shift+I, or ⌘+⌥+I on macOS. The quickest way is to right-click the element and choose “Inspect” in the menu: the node you need is highlighted at once.

  1. In the markup tab (“Inspector” in Firefox, “Elements” in the other browsers) compare the DOM with the source code. The browser may have rebuilt the markup, and the DOM shows what it actually received.
  2. In the rules panel find your rule. If it is missing, the selector failed to match the element or the rule was discarded; if a declaration is struck through, it was overridden or its value is invalid.
  3. In the “Computed” tab look at the final values of the properties — the ones the browser actually applied.
  4. The “Layout” tab has the details on Grid and Flexbox. In Firefox the box model diagram is there too; in the other browsers it is in the “Computed” tab.
  5. Check the markup in Markup Validation Service and the CSS in CSS Validator: both services are run by the W3C.

The rule is not visible in DevTools

The cause: the selector fails to match the element — a typo in the class, the wrong combinator — or one selector in the list is invalid, and the browser discarded the entire block. A mistake in a pseudo-class name makes the whole selector invalid; a class that does not exist does not, it merely selects nothing.

csswhat not to do
/* :hovr — a typo: the whole block is discarded */.card,.card:hovr {  border-color: #0b57d0;}
  • Fix the typo and check that the rule has appeared in the rules panel.
  • Put a selector the browser may fail to understand into a separate rule or into :is(): inside it an unknown alternative does not break the rest.

The declaration is struck through

The cause: it was overridden by a more specific rule or by one higher up the cascade, or the value is invalid — DevTools strikes through such declarations as well. The winning declaration is shown without a strike-through.

cssstyles.css
/* class: 0-1-0, wins */.special {  color: orange;} /* type: 0-0-1, struck through on em.special */em {  color: hotpink;}
  • Compare the specificity and either match it or change the order of the rules — without !important.
  • If the value is invalid, check its type: background-color: 45deg is discarded by the browser.

The declarations after one of them stop working too

The cause: a semicolon is missing. The browser reads red background-color: green as one invalid value for border-color and discards both declarations. An unclosed /* comment likewise hides all the CSS up to the next */ or to the end of the style sheet.

csswhat not to do
p {  border-color: red  background-color: green;}

The property is not supported by the browser

The cause: the browser ignores properties and values it does not know, and nothing breaks — the style silently fails to apply. DevTools usually flag such declarations. For support see the compatibility table at the bottom of the property’s page in the MDN docs.

cssstyles.css
.box {  /* the old syntax — for browsers without the new one */  display: inline-flex;  display: inline flex;}

Write the old syntax first and the new one after it: a browser that does not understand the new syntax is left with the old.

Unclosed element strong

The cause: a tag is left unclosed, and its effect spreads across the document: the browser wraps every following chunk of text in <strong> until the end of the page. This is how the validator reports an unclosed element; the neighbouring messages are End tag li implied, but there were open elements.

htmlwhat not to do
<ul>  <li>The <strong>tag is unclosed, and everything below becomes bold</li>  <li>The second item</li></ul>
  • Check the page in Markup Validation Service: every message comes with a line and column number.
  • Fix several errors at a time and validate again: one error often drags a chain of further errors behind it.

End tag strong violates nesting rules

The cause: the tags overlap rather than nest inside each other. The browser will rearrange them according to its own rules, and the result may differ from what was intended.

htmlwhat not to do
<p><strong>important <em>very</strong> important</em></p>
htmlthe right way
<p><strong>important <em>very</em></strong> <em>important</em></p>

End of file reached when inside an attribute value. Ignoring tag

The cause: an attribute value has no closing quote. The rest of the document became part of the value, and the element — a link, for example — disappeared from the page; the validator may add an “Unclosed element” message for elements that are in fact closed.

htmlwhat not to do
<a href="https://example.com/>Example</a>

The page looks outdated: quirks mode

The cause: the document does not start with <!doctype html>, so the browser switched to quirks mode, which imitates Navigator 4 and Internet Explorer 5. Firefox writes a warning about this to the console of the developer tools.

javascriptDevTools console
document.compatMode
textexample output
"BackCompat"

"BackCompat" means quirks mode, "CSS1Compat" — standards mode. Put <!doctype html> as the very first line of the document.

Layout problems

SymptomCauseWhat to do
A block is wider than specified in widthwith content-box, padding and border are added to widthbox-sizing: border-box; the section “The box model and sizing”
A heading’s margin “sticks out” beyond the parentthe margin of the first child has collapsed with the parent’s marginpadding or border on the parent; the section “The box model and sizing”
A flex item does not shrink, the text overflowsflex items have min-width: automin-width: 0; the section “Flexbox”
z-index: 9999 does not raise the elementthe element is inside another stacking contextset z-index on the element that creates the context; the section “Positioning and z-index”
position: sticky does not stickno top is set, or an ancestor has overflow: hiddenset the threshold, remove overflow from the wrapper; the section “Positioning and z-index”
Horizontal scrolling on a phoneno <meta name="viewport">, a fixed width or an image without max-widththe section “Responsive design”
The form is submitted by any buttonin a form, <button> has the type submit by defaulttype="button" on the other buttons; the section “Forms and input fields”
::before does not appearthe content property is not setcontent: ""; the section “Selectors”

Section sources

the section is written from these pages

Standards and their status

HTML is described in the HTML Living Standard maintained by WHATWG — a single continually updated document with no version numbers. CSS is described by a set of W3C modules, and which of them are stable is fixed by the CSS Snapshot: at the moment that is CSS Snapshot 2026, dated 22 June 2026.

DocumentWhat it definesStatusReplaced or extended by
HTML Living Standardelements, attributes, HTML parsing, formsWHATWG Living Standardabsorbed HTML 4, XHTML 1 and DOM2 HTML
CSS Snapshot 2026which modules make up CSS as of 2026W3C Group Note, 22 June 2026superseded CSS Snapshot 2025
CSS 2.1the core of CSS: flow, boxes, positioningREC, 7 June 2011many sections have been replaced by level 3 modules
Selectors Level 4selectors, including :is(), :where(), :has()WD, 22 January 2026extends Selectors Level 3 (REC)
CSS Cascading and Inheritance Level 5the cascade, inheritance, @layer cascade layersCR, 13 January 2022extends and replaces Level 4
CSS Box Model Module Level 3margin and paddingREC, 11 April 2024replaces sections 8.1–8.4 of CSS 2, except 8.3.1 on margin collapsing
CSS Flexible Box Layout Module Level 1FlexboxCRD, 14 October 2025—
CSS Grid Layout Module Level 2Grid and subgridCRD, 26 March 2025extends and replaces Grid Level 1
Media Queries Level 4media queries, range syntaxCRD, 19 February 2026replaces Level 3; prefers-* are defined in Level 5 (WD)
CSS Positioned Layout Module Level 3position, stickyWD, 7 October 2025—
CSS Nesting Module Level 1rule nestingWD, 22 January 2026—
CSS Custom Properties for Cascading Variables Level 1--name and var()CR, 16 June 2022—

W3C statuses go from draft to standard: WD → CR → PR → REC. WD (Working Draft) is a working draft. At the CR (Candidate Recommendation) stage the specification is checked with tests and implementations; CRD is a draft revision of CR. PR (Proposed Recommendation) is the last step before REC (Recommendation), a finished standard. The current status of each module is on the CSS current work page.

Why HTML and CSS have no versions

WHATWG maintains HTML as a Living Standard: the document is continually corrected and extended rather than frozen as a “finished version”. In 2011 the W3C wanted to ship a completed “HTML5”, while WHATWG wanted to keep a living standard; in 2019 the two organisations agreed to maintain a single version of HTML — the HTML Living Standard. “HTML5” became a buzzword for modern web technologies, and the HTML standard’s own answer to the question “Is this HTML5?” is: yes.

CSS has no versions; it has levels. CSS 1 and CSS 2 were single documents, after which each module evolves on its own: Selectors Level 4, Grid Level 2. “CSS3” is a loose name for everything after CSS 2.1, and “CSS4” does not exist: only individual modules reach level 4.

What has changed in recent editions

  • Selectors: CSS Nesting Module Level 1 has entered the CSS Snapshot for the first time — in the group of modules that already work widely but still require testing and refinement.
  • Selectors: ::marker, :focus-within, :placeholder-shown, :valid, :invalid, :required, :optional, :modal, :any-link and selector lists in :nth-child() have joined the list of features that browsers are allowed to ship before the CR stage.
  • Responsive design and forms: the env() function with the safe-area-inset-* variables and the accent-color property have been added to the same list.

Outdated documents that are still cited

  • HTML 4 (1997) and XHTML 1.0 (2000): their content has been absorbed into the HTML Living Standard. The standard no longer calls the XML syntax of HTML XHTML.
  • The W3C’s “HTML5” as a separate finished version: the HTML Living Standard has replaced it.
  • CSS 1: the working group considers the specification outdated.
  • CSS 2: CSS 2.1 has replaced it, and parts of CSS 2.1 — level 3 modules.

How to tell whether a property is safe to use

A specification’s status says something about the stability of the text, not about support: the CSS Snapshot states outright that it includes modules by stability, not by how widely browsers support them. For support, look at the Baseline labels in the MDN docs — they take into account Chrome, Edge, Firefox and Safari on desktops and phones.

LabelWhat it means
Widely availablehas worked in all of these browsers for at least 2.5 years in a row
Newly availableworks in their latest stable versions; older versions may not support it
Limited availabilitynot yet available in every browser
Deprecatedoutdated, do not use it in new code

Baseline is a summary of support, not a replacement for testing: it does not tell you how a feature behaves on old devices, in in-app browsers, or with screen readers. The WCAG and ARIA accessibility standards are covered in the “Accessibility (a11y)” reference.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

9 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “HTML and CSS” topic
13 sections
Another reference · Backend

HTTP and REST

Verified 1 Nov
All references · 61