Open the guide contents
Before you start
This guide follows one HTML page: you’ll create it, connect a CSS file and change it one step at a time. Short examples isolate one rule; at the end, you’ll use the concepts together in a services page.
You’ll need a browser and a code editor, such as Visual Studio Code. Edit the files in the editor and view the page in the browser. If tags, classes and elements inside other elements are new to you, you can read the HTML guide first.
Each example shows a CSS rule and its effect in the browser. Links for further reading are at the end.
To follow one example from start to finish, read create the page and connect the files, read the first rule, selectors, space around elements, Grid, media queries and the final exercise. The other chapters give you more detail.

What you can experiment with
You can try CSS rules on an HTML page and see each change in the browser. To begin, create a folder and open it in the code editor you prefer. In the next chapter, you’ll add a page with a heading and paragraph, then connect a CSS file.
The first try changes the paragraph from blue to red. In the following chapters, you’ll keep editing the same files, adding one rule at a time.
1. Create the HTML page and connect its CSS
For the first try, you need a page to change. Create index.html with a heading and paragraph, then add style.css and connect it to the page. The browser can then apply the CSS rule you’ll write below.
1. Create two files in the same folder
Create a folder called css-practice. Open it in your code editor and create index.html and style.css inside it. Put this content in index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSS practice page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<article>
<h1>Consulting</h1>
<p>We help you set the project priorities.</p>
</article>
</body>
</html>2. Write the CSS rule
In style.css write:
p {
color: royalblue;
}3. Check the result
Save both files, then open index.html in a browser. The blue paragraph appears below the “Consulting” heading. In the HTML, <link> connects the page to style.css; in the CSS, p selects paragraphs and color sets their text color. Change royalblue to tomato, save style.css and reload the page: the text turns red. If it does not, check that both files are in the same folder and that href contains the exact name style.css.
The other two ways to write CSS
For a single page, you can put a rule in <style> inside <head>:
<style>
p { color: royalblue; }
</style>For one element, you can use its style attribute:
<p style="color: royalblue;">Blue text</p>Both make the text blue. When rules recur across pages, an external file is easier to maintain. Inline styles can override other rules; the cascade chapter explains why.
2. Read the CSS rule you just added
The page you just created shows a blue paragraph. Let’s look at the rule that produces this result and identify its parts: selector, property and value.
A CSS rule has a selector and a block in curly braces. The selector tells the browser which elements the declarations apply to.
p {
color: royalblue;
}pis the selector: it matches every paragraph.color: royalblue;is a declaration: propertycolor, valueroyalblue.
A colon separates a property from its value. A semicolon ends the declaration. Spaces and line breaks make the code easier to read.
The browser ignores a declaration with an invalid value: color: 20px; does not set a color. The other valid declarations in the rule still apply.
Interactive example
Change a paragraph’s color
The paragraph always has the same text. With color: #8bc9ef the text is blue; with color: #efb38b it is orange.
3. CSS comments
The CSS file now has a rule for the paragraph. You can add a comment beside it to remember what it does; the browser ignores comments when displaying the page.
A comment is a note for people reading the code. The browser ignores it when applying styles, so the comment does not change the appearance of the page.
A single-line comment
Write the text between /* and */:
/* Paragraph text color */
p {
color: royalblue;
}The comment describes the rule. The declaration color: royalblue; makes the paragraph text blue.
A multi-line comment
The same symbols can enclose a longer comment:
/* Paragraph text should stay
readable on the light background. */
p {
color: darkblue;
}The note explains the color choice; the p rule applies darkblue to the paragraph text. Always close a comment with */, otherwise the code that follows can also be ignored.
4. Choose which elements to change: selectors
The p rule changes the color of every paragraph. Now let’s choose which elements a rule applies to, first by tag and then by class.
Select all elements of one type
This HTML contains two paragraphs:
<p>First paragraph</p>
<p>Second paragraph</p>This rule selects p elements:
p {
color: blue;
}Result: both paragraphs are blue because both are p elements.
Select elements with a class
To change only some paragraphs, you can give them a class. Here only the first has the avviso class (Italian for “notice”):
<p class="avviso">First paragraph</p>
<p>Second paragraph</p>In CSS, the dot before the name indicates a class:
.avviso {
color: blue;
}Result: the first paragraph is blue. The second does not change because it does not have the avviso class. If you also add class="avviso" to the second, both become blue: a class can be used on multiple elements.
More selectors: IDs
Select an element with an ID
An id identifies a single element on the page. Here the ID belongs only to the first paragraph:
<p id="introduction">First paragraph</p>
<p>Second paragraph</p>In CSS, the # before the name indicates an ID:
#introduction {
color: blue;
}Result: only the first paragraph is blue. Do not assign the same ID to multiple elements on the page.
Select based on position in the HTML
Here <div class="card"> contains a paragraph. card is the class name in the HTML; in CSS, .card selects that element. The second paragraph comes after the div, so it is outside it:
<div class="card">
<p>Text inside the card</p>
</div>
<p>Text outside the card</p>.card p {
color: blue;
}Result: the text inside the card is blue; the text outside does not change. The space in .card p means: select paragraphs inside an element with the card class, even when they are nested more deeply.
More selectors: children, combined classes and groups
Direct child or element further inside?
Both paragraphs are inside the div with the card class. The first is directly inside it; the second is inside a section element.
<div class="card">
<p>Direct child</p>
<section>
<p>Inside the section</p>
</section>
</div>.card > p {
color: blue;
}Result: only “Direct child” is blue. Here > selects paragraphs directly inside the card. If you use a space instead, .card p, both turn blue.
Two more ways to combine selectors
An element can have multiple classes. Here the first paragraph has both avviso and urgent; the second only has avviso:
<p class="avviso urgent">First paragraph</p>
<p class="avviso">Second paragraph</p>.avviso.urgent {
color: blue;
}Result: only the first paragraph is blue. With no space, .avviso.urgent finds an element that has both classes. The space in the HTML attribute separates class names; the space in a CSS selector has the meaning explained above: “inside”.
A comma instead lists separate selections. With the following HTML and CSS, both the heading and paragraph turn blue:
<h2>Heading</h2>
<p>Paragraph</p>h2, p {
color: blue;
}The comma applies the same declaration to every h2 and every p; they do not need to be inside one another.
Check a change proposed by AI
Before choosing a selector, check which elements you want to change: p selects every paragraph; .card p selects only paragraphs inside an element with class="card". If that class is not in the HTML, the rule matches nothing.
In the first result, p changed every paragraph. To change only paragraphs inside a card, use a descendant selector:
.card p {
color: royalblue;
}Interactive example
Color every paragraph or just one
There are two messages. The first has the avviso class; the second does not. With p both turn blue. With .avviso only the first turns blue. Choose a selector and compare the result with the HTML.
5. Understand which rule wins: cascade
You now know how to choose the elements you want to change. If two rules set different colors on the same element, the browser has to choose one: this choice is called the cascade.
The cascade decides which value to use for each property. For example, one rule can set the color and another can set the text size.
Start with normal declarations, without !important, in the same stylesheet and without @layer. Under these conditions:
- The selector with higher specificity wins.
- When specificity is equal, the later declaration wins.
<p class="note">Testo / Text</p>.note { color: orange; }
p { color: royalblue; }The text is orange. .note contains a class and wins over p, even though p is written later.
Deep dive: comparing specificity
How to compare specificity
Count three groups and compare them from the left: IDs; classes, attributes and pseudo-classes; types and pseudo-elements. #intro is (1,0,0), .note (0,1,0), p (0,0,1), .group p (0,1,1). The first unequal group decides. Spaces and > add no specificity.
The full cascade also considers style origin, importance and @layer layers before specificity. Normal inline styles beat normal rules in author stylesheets. !important changes a declaration's precedence, not its selector's specificity. Identify the conflict before adding it.
Interactive example
Specificity and order are different criteria
The class .note beats p. If both rules use .note, the later one wins. The controls show these three cases; the losing declaration is crossed out.
6. Understand where a value comes from: inheritance
The cascade compares rules that apply to the same element. A value can also come from the HTML element around it: let’s see when color passes from a parent to a paragraph.
If the paragraph has no color rule of its own, it can use the color of the div around it. This passing of some values is called inheritance.
<div class="parent">
<p>Testo / Text</p>
</div>.parent {
color: orange;
border: 2px solid orange;
}The paragraph inherits color: its text is orange. It does not inherit border: only the parent has a border. font-family and line-height normally inherit too; width, margin and padding do not.
If you write p { color: royalblue; }, the paragraph turns blue. A value assigned to the child takes precedence over an inherited value, even if the parent's selector is more specific. Specificity is not compared between different elements.
Deep dive: inherit, initial and unset
inherit requests the parent's value; initial uses the property's initial value; unset inherits inherited properties and uses the initial value for others. initial does not mean “restore browser styles”.
Interactive example
Color inherits; border does not
The parent has orange text and a border. Without its own rule, the paragraph takes its parent’s color. Assigning a color to the paragraph changes only its text; the border stays on the parent.
7. Understand how elements are arranged: flow
So far, we have changed how elements look, not their order. Without Flexbox or Grid, the browser displays the heading and paragraph in the order they appear in the HTML.
Normal flow is how the browser lays out elements before Flexbox, Grid or positioning. These examples use horizontal, left-to-right text.
display: block: the element starts on a new line and, with an automatic width, takes the available horizontal space. Paragraphs anddivelements normally behave this way.display: inline: the element participates in a line of text. On a normalspan,widthandheightdo not set its dimensions.display: inline-block: it stays in the line but acceptswidthandheight.display: none: the element and its descendants generate no boxes and take no layout space. They normally disappear from the accessibility tree too.
<span class="item">A</span>
<span class="item">B</span>With .item { display: block; }, A and B occupy two lines. With inline they participate in the same line if there is room. The box behavior changes; the HTML order stays the same.
visibility: hidden hides an element while keeping its space. opacity: 0 makes it transparent but may leave it clickable and keyboard-focusable: it is not a substitute for display: none.
Interactive example
display changes box behavior
Each element has width: 80px. With inline this width does not apply to the spans. With block it applies and each element starts a line. With inline-block it applies without forcing a new line.
8. Understand occupied space: Box Model
The browser has placed the heading and paragraph and given each space. The Box Model describes the parts that make up the space each element occupies.
From the center outward, the four areas are:
- Content: text, an image or child elements.
- Padding: space between content and border. It receives the element's background.
- Border: the edge around content and padding.
- Margin: space outside the border. It is transparent.
.box {
width: 120px;
padding: 10px;
border: 2px solid;
margin: 16px;
}With the initial value box-sizing: content-box, width measures the content. The width to the outer border is 120 + 10 + 10 + 2 + 2 = 144px. Margins remain outside: in this example the horizontal space occupied, including margins, is 176px.
With box-sizing: border-box, the 120px include content, padding and border. The content shrinks to 96px. Margin still stays outside.
Shorthand properties and vertical margins
padding: 10px 20px means 10px on top and bottom, 20px on the left and right. With four values the order is top, right, bottom, left.
Deep dive: vertical margins
In block flow, adjacent vertical margins can collapse: two positive margins of 16px and 24px can produce 24px, not 40px. Margins between flex or grid items do not collapse.
This rule adds internal space and a border to the card. The text remains inside it:
.card {
padding: 1.5rem;
border: 1px solid #52616b;
}Deep dive: browser defaults and resets
Browser defaults and CSS resets
The browser applies some styles even without your CSS: for example, it adds margins to the body and paragraphs. These values can vary between browsers and affect the layout of elements.
To start from a more consistent base, many projects use a CSS reset: a set of rules that changes or removes some default styles. This code is only an example to show what a reset can look like. It is not a universal standard to copy: every project has its own structure and content, so its reset should reflect its needs.
*, *::before, *::after {
box-sizing: border-box;
}
body, h1, h2, h3, h4, p, ul, ol, figure {
margin: 0;
}
img {
max-width: 100%;
height: auto;
}
button, input, select, textarea {
font: inherit;
}The first rule uses border-box to make sizing more predictable. The second removes the default margins from the listed elements so you can set the spacing yourself. Images do not exceed the available width, and form controls use the inherited font.
Interactive example
width measures content or the whole box
The element has width: 120px, padding of 10px and a 2px border. With content-box, content, padding and border add up to 144px. With border-box, the total width stays 120px. The browser calculates the measurements below the example.
9. Adapt sizes and content: units and overflow
Now that you know about content, padding and margins, let’s look at how to measure them. Some measurements depend on the element around the text or on the window width.
A percentage needs a reference. In the examples below, width: 50% means the element is half as wide as the element around it, not half the screen.
px: CSS pixels, not necessarily physical screen pixels.%: The reference depends on the property: for width, normally the containing block’s width.rem: The root html element’s font size.em: For font-size: the parent’s font size. For padding and many other lengths: the element’s own font size.vw / vh: 1vw is 1% of viewport width; 1vh is 1% of its height. On mobile, dvh follows the dynamic visible height.
If html has a 16px font, 2rem is 32px. If the parent has a 20px font, font-size: 1.5em on the child gives 30px; on that same child, padding: 1em gives 30px.
Automatic sizing and limits
.box {
width: 100%;
max-width: 600px;
min-height: 100px;
}The box uses its container's width, up to 600px. It is at least 100px tall and can grow with its content. In contrast, height: 100px imposes a height that may not fit the text.
On a block in normal flow, width: auto fits the available space while accounting for padding, border and margins. width: 100% assigns a percentage: with content-box, padding and border are added.
Content that exceeds its space: overflow
overflow: visible lets content remain visible outside the box; hidden clips it; auto allows scrolling when needed. For long text without spaces, you can use overflow-wrap: anywhere. Understand the cause of overflow before hiding it.
calc(100% - 2rem) combines different measurements. clamp(1rem, 2vw, 1.5rem) chooses the middle value while keeping it between the stated minimum and maximum.
Interactive example
50% depends on the container width
The child has width: 50%. In a 160px container it measures 80px; in a 240px container it measures 120px. Change the parent width: the child’s rule stays the same.
10. Keep text and colors readable
Sizing helps content fit on the page. Now let’s check that text, line spacing and colors stay readable when the page is zoomed in.
color sets the text color. background-color sets the box background. They are independent properties.
body {
font-family: Arial, sans-serif;
font-size: 1rem;
line-height: 1.5;
color: #222222;
background-color: #ffffff;
}
p {
max-width: 65ch;
}font-family is a list: the browser uses the first available font; sans-serif is a generic fallback family. font-size sets the size; font-weight sets the weight, such as 400 for normal and 700 for bold.
line-height: 1.5, without a unit, is a multiplier: 16px text has a 24px line height. When the factor is inherited, each child multiplies it by its own font size. 65ch is a width based on the “0” character in the current font, not an exact character count.
You can write a color as a name (red), hexadecimal (#ff0000), rgb(255 0 0) or hsl(0 100% 50%). rgb(255 0 0 / 50%) makes only that color transparent. In contrast, opacity: 0.5 makes the whole element, including its children, translucent.
11. Check control states
So far, the rules changed appearance without responding to user actions. State selectors can show, for example, when a link is under the pointer or reached with the keyboard.
A selector can depend on an element's attributes or state:
[type="email"]matches elements with that attribute and value.:hovermatches the element under the pointer.:focus-visiblematches a focused element when the browser determines that a visible indicator is needed, normally during keyboard navigation.:first-childmatches an element that is its parent's first child.
a:hover { color: orange; }
a:focus-visible { outline: 3px solid royalblue; }
input[type="email"] { border: 1px solid; }
li:first-child { font-weight: bold; }
.note::before { content: "→ "; }Pseudo-classes have one : and select a state or condition. Pseudo-elements, such as ::before and ::after, have two : and let you style a generated part of an element. Here, content adds an arrow before the text. Keep essential content in HTML.
Focus identifies which control receives keyboard input. Do not remove its indicator without providing a visible replacement.
Interactive example
The :focus selector matches the active control
Click the field or reach it with Tab: the blue outline defined by input:focus appears. When focus leaves the field, the outline returns to its base value. This example uses :focus, which always matches while the field has focus.
12. Arrange elements in one direction: Flexbox
When the page has several service items, you can arrange them in a row or a column. Flexbox lets you control that layout.
Apply display: flex to the container. Its direct children become flex items. You do not need to set display: flex on every child.
.container {
display: flex;
flex-direction: row;
gap: 12px;
justify-content: flex-start;
align-items: center;
}Flexbox places children along a main axis. flex-direction chooses the direction. In our examples, with horizontal writing, row is a row and column is a column. The other axis is called the cross axis.
justify-contentaligns and distributes free space along the main axis.align-itemsaligns children along the cross axis.gapsets the space between children without adding space at the container edges.flex-wrap: wrapallows multiple lines when space runs out. The initial value isnowrap.
How children divide space
On children, flex-grow controls growth into free space; flex-shrink controls shrinking when space runs out; flex-basis sets the starting size on the main axis. flex: 1 1 0 sets them together: grow 1, shrink 1, basis 0.
The automatic minimum size can stop a child from shrinking below its content size. When content needs to fit, also check min-width: 0 and text wrapping. Flexbox can wrap, but each line distributes its own space: it does not create shared columns across lines.
Interactive example
row and column change the main axis
The container has three direct children: A, B and C. With row they form a row; with column they form a column. The gap stays 12px. Only flex-direction changes.
13. Arrange elements in rows and columns with Grid
Flexbox arranges items in one direction. To control rows and columns together, Grid lets you define both.
Apply display: grid to the element that contains the items. Its rules define columns and rows; the browser places the items into cells in HTML order.
.container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}1fr 1fr defines two columns with equal shares of the available space. fr represents a fraction of the space remaining after fixed sizes and gaps, subject to track constraints. 1fr 2fr gives the second column twice the share of the first.
repeat(3, 1fr) repeats 1fr three times. minmax(0, 1fr) creates a column with a zero minimum and a one-fraction maximum: it prevents the track's automatic minimum from widening it for long content. The content may still need wrapping rules.
On a child, grid-column: span 2 requests two columns. grid-row: span 2 requests two rows. The container creates the tracks; the child specifies which to occupy.
When to choose Grid or Flexbox
Use Flexbox to distribute items along a row or column. Use Grid to define shared columns and rows. A grid container can have a flex container inside one of its cells.
When an element with the .cards class contains three elements with the .card class, Grid first arranges them in one column. Put the Grid rule on .cards; the .card elements stay inside it:
.cards {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
}Interactive example
The container defines the column count
There are four children: A, B, C and D. With two columns they form two rows; with one column they form four rows. Each column gets an equal share of the available space.
14. Adapt the page to available space: media queries
You have defined columns with Grid. A media query lets you change their number when the browser window gets narrower or wider.
A media query applies some rules only when a condition is true. Here, the condition checks the width of the area where the browser displays the page, called the viewport.
.container {
display: grid;
grid-template-columns: 1fr;
gap: 12px;
}
@media (min-width: 640px) {
.container {
grid-template-columns: 1fr 1fr;
}
}Below 640px the grid has one column. From 640px inclusive it has two: min-width includes the threshold. The rule inside the media query does not remove other properties: display and gap still apply.
Mobile first means writing the baseline for small widths and adding changes for larger ones. The threshold is called a breakpoint: choose it when the content needs a change. 640px is this example's threshold, not a universal rule.
The HTML tag <meta name="viewport" content="width=device-width, initial-scale=1"> lets mobile browsers use the device width as the layout viewport. Fluid measurements and max-width limits also matter between breakpoints.
Using the same “one column first” approach, the final project switches to three columns from 800px. The threshold is higher than the two column example because three cards need more room:
@media (min-width: 800px) {
.cards { grid-template-columns: repeat(3, minmax(0, 1fr)); }
}Interactive example
The condition changes at 640px inclusive
At 639px you see one column. At 640px you see two columns. The buttons set the example’s actual viewport width; the CSS rule stays the same.
15. Find out why a rule does not work
The page now uses selectors, measurements and layout rules. If a change does not have the expected effect, the browser tools can help find the rule responsible.
Open the browser's developer tools by choosing Inspect on the element. Styles shows declarations; Computed shows their resulting values. Check in this order:
- Did the file load? In Network, check that the CSS loaded without errors and that the path is correct.
- Does the selector match? Check the selected element's tag, classes and nesting.
- Is the declaration valid and does it win? A warning may indicate an invalid value. A crossed-out declaration may have been overridden: find the active one.
- Is the value inherited? Distinguish the element's rules from values coming from its parents.
- Does the property act in this context?
widthdoes not size an inline span;justify-contentdoes not distribute free space when there is none. - How large is the box? Read content, padding, border and margin. If there is a media query, check the viewport width.
Change one declaration at a time and check the computed value. Edits in developer tools are temporary: copy them into the CSS file to keep them.
16. Concept reference
Before putting the examples together in the final page, here is a map of the concepts so far and the questions each one answers.
- Which elements receive the rule?
selettore / selector- Which declaration wins?
cascata / cascade- Where does the child’s value come from?
ereditarietà / inheritance- How does it participate in flow?
display, position- How much space does it take?
width, padding, border, margin, box-sizing- What is the measurement relative to?
%, rem, em, viewport- How are children arranged?
flex, grid- When does the rule group apply?
@media
17. Put the examples together: three content blocks
Now you can bring the examples together in a services page: the HTML contains the content blocks, and CSS controls their colors, spacing, grid and layout at different window widths.
1. Describe the result
If you use an AI tool, you could ask:
Create an HTML page with three service blocks and a separate CSS file. Start with one column; from 800px up use three columns. Do not clip long text. Links need a visible focus state. Explain the rules and how to check the result.
You can also build the page yourself: the browser checks are the same.
2. Update the page you created
Return to index.html and style.css in the css-practice folder. Replace the contents of index.html with the code below, then add the rules to style.css. This keeps the final page in the same project you started in chapter 1. The example links lead to the Contact section on the page.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Services</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1>Our services</h1>
<div class="cards">
<article class="card">
<h2>Consulting</h2>
<p>We define the project priorities.</p>
<a href="#contact">Contact us</a>
</article>
<article class="card">
<h2>Design</h2>
<p>We design a solution for your content.</p>
<a href="#contact">Contact us</a>
</article>
<article class="card">
<h2>Support</h2>
<p>We help you maintain the project.</p>
<a href="#contact">Contact us</a>
</article>
</div>
<p id="contact">Contact: example@example.com</p>
</main>
</body>
</html>.card {
box-sizing: border-box;
}
body {
margin: 0;
font-family: Arial, sans-serif;
line-height: 1.5;
}
main {
max-width: 72rem;
margin: 2rem auto;
padding: 0 1rem;
}
.cards {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
}
.card {
padding: 1.5rem;
border: 1px solid #52616b;
overflow-wrap: anywhere;
}
.card p {
color: royalblue;
}
a {
color: #004c80;
}
a:focus-visible {
outline: 3px solid #004c80;
outline-offset: 3px;
}
@media (min-width: 800px) {
.cards {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}Grid arranges the cards; minmax(0, 1fr) lets columns shrink; overflow-wrap breaks very long words. The media query adds three columns from 800px, while the base remains one column. :focus-visible shows keyboard focus.
3. Check and revise
- Open
index.htmland try widths below and above 800px: check that the cards switch from one to three columns. - Lengthen a heading and description, then zoom in: the text should remain visible and the cards should grow.
- Press Tab until you reach the links: the focus must be visible. Try your project’s real content too.
If the cards are still too narrow at 800px for your content, raise the threshold in the media query and try again. That number depends on the content; it is not a universal size. A suggestion to add overflow: hidden might merely conceal the problem.
18. Check the fundamentals
Ten questions on the concepts in this guide. Every answer includes an explanation.
19. Position elements and manage stacking
This extra section returns to the content blocks in the final page. With position, you can place a label inside one and understand how elements overlap.
position controls whether an element stays in its normal place, moves from that place or uses another element as a reference.
static: the initial behavior.top,right,bottomandleftdo not move the element.relative: keeps its space in flow; offsets start from its original position.absolute: leaves flow, so other elements reserve no space for it. In this example it uses the nearest ancestor with apositionother thanstaticas its reference.fixed: leaves flow and normally uses the viewport as its reference, staying in place during scrolling.sticky: keeps its space and sticks at the specified threshold, such astop: 0, during scrolling in the relevant container and within its containing block's limits.
.parent {
position: relative;
}
.child {
position: absolute;
top: 12px;
right: 12px;
}The child is positioned 12px from the top and right of the reference established by .parent. Without offsets, position: relative does not move the parent. Other properties, such as transform, can establish references for absolute and fixed elements too: check them if the reference is unexpected.
Overlapping and z-index
z-index controls the stacking order of positioned elements and flex or grid items. It is not a global ranking: it operates within the element's stacking context. Properties such as transform and opacity below 1 can create a separate context. A child with z-index: 9999 stays inside its parent's context.
Interactive example
absolute removes an element from flow
With static, A takes space and B follows it. With absolute, A moves to the parent’s corner and B moves into the space it left. The parent always has position: relative.
20. Keep values consistent: CSS variables
The page already uses colors and CSS rules. If several elements share a color, a variable lets you save that value once and reuse it.
A custom property, often called a CSS variable, stores a value under a name starting with --. var() uses that value in another declaration.
:root {
--accent: royalblue;
}
.note {
color: var(--accent, blue);
}
.section {
--accent: orange;
}:root selects the document root, which is html. Here it assigns a value available to descendants through inheritance. A .note outside .section is blue; inside .section it is orange because it inherits the value redefined there.
Custom properties participate in the cascade and, in the form shown, inherit. The second argument in var(--accent, blue) provides a fallback for an undefined variable. It does not fix an existing value unsuitable for the property: if --accent: 20px, color: var(--accent, blue) does not automatically use blue.
Interactive example
Two elements read the same value
A and B both use color: var(--accent). Changing --accent changes both colors. The two color declarations stay the same.
21. Evaluate movement: transform and transition
As a final extra topic, we’ll add movement to an element and see how to make the transition less noticeable for people who prefer reduced motion.
These properties come after the fundamentals. transform changes an element's visual rendering: it can translate, rotate or scale it. translateX(8px) displays it 8px to the right without moving neighboring elements in flow.
.box {
transform: translateX(0);
transition: transform 200ms ease;
}
.box:hover {
transform: translateX(8px);
}
@media (prefers-reduced-motion: reduce) {
.box { transition: none; }
}transition interpolates a value change: here it affects transform, lasts 200 milliseconds and uses the ease timing function. The :hover state changes the value; the transition defines the passage. It does not change the final value.
A transition requires a change and interpolable values. An animation with @keyframes can instead define a sequence of values. The prefers-reduced-motion media query lets you respect a preference for less motion.
Sources and further reading
To check how a property works or look up a detail from the examples, these resources link to documentation and reference tools.