CSS has changed a lot in the last few years. Things that once needed JavaScript, a preprocessor like Sass, or a pile of media queries can now be written in plain CSS that runs in every modern browser.
In this chapter we study four of the most useful modern features:
:has()— select an element based on what it contains (the long-awaited "parent selector").Native nesting — write rules inside other rules, without Sass.
min(),max()andclamp()— sizes that adapt smoothly between limits.Logical properties —
margin-inline,padding-blockand friends, which work for any writing direction.
You should be comfortable with Combinators & Attribute Selectors, Pseudo-classes & Pseudo-elements, Specificity, Inheritance & the Cascade and CSS Units before reading this chapter. Every example here was tested in a current version of Chrome.
Browser Support at a Glance
"Modern" does not mean "experimental". All four features are marked Baseline: Widely available on MDN, which means they have worked in Chrome, Edge, Firefox and Safari for at least 30 months.
| Feature | Works in all major browsers since | Safe to use today? |
|---|---|---|
clamp(), min(), max() | July 2020 | Yes |
Logical properties (margin-inline etc.) | September 2021 | Yes |
:has() | December 2023 | Yes, for normal websites |
| Native CSS nesting | December 2023 | Yes, for normal websites |
If you must support very old browsers (for example an old company kiosk), :has() and nesting are the two to be careful with. We'll see how to fail safely later in the chapter.
1. The :has() Pseudo-class
For years, CSS selectors could only look down and forward in the document: from a parent to its children, or from an element to the siblings after it. You could style "a paragraph inside a card", but never "a card that contains a paragraph". That needed JavaScript.
A:has(B)matches every element A that has at least one B relative to it. By default B is searched among A's descendants; B can also start with a combinator (>,+,~) to look at children or following siblings.
Read :has() as "which has". The element that gets styled is always the one before :has, not the one inside the brackets.
Example 1: style a card only if it contains an image
<div class="card">
<img src="photo.jpg" alt="" width="40" height="40"> Card with image
</div>
<div class="card">
<span class="badge">New</span> Card with badge
</div>.card {
border: 2px solid #ccc;
padding: 12px;
}
/* a card that has an img anywhere inside it */
.card:has(img) {
border-color: green;
}
/* a card that has a .badge as a DIRECT child */
.card:has(> .badge) {
background-color: #fff3cd;
}Output: the first card gets a green border; the second card keeps its grey border but gets a pale yellow background. Same class, different styles, decided purely by the content.
Example 2: react to the state of something inside
Because the argument of :has() can contain pseudo-classes, a parent can react to the state of its children:
/* fade the submit button while any field in the form is invalid */
form:has(input:invalid) .submit {
opacity: 0.4;
}
/* make a label bold and red when the checkbox inside it is ticked */
label:has(input:checked) {
font-weight: bold;
color: crimson;
}<form>
<input required>
<button class="submit">Send</button>
</form>
<label><input type="checkbox" checked> I agree</label>Output: while the required field is empty, the "Send" button is faded to 40% opacity. The label text "I agree" is bold crimson because its checkbox is checked. Untick it and the label goes back to normal — instantly, with zero JavaScript.
Example 3: look at the next sibling
/* an h2 that is immediately followed by a p */
h2:has(+ p) {
margin-bottom: 0;
}Before :has(), h2 + p could only style the paragraph. Now we can style the heading based on what comes after it — effectively a "previous sibling" selector.
Example 4: quantity queries
/* a list with 4 or more items → show it in two columns */
ul:has(> li:nth-child(4)) {
columns: 2;
}Step by step: li:nth-child(4) only exists if the list has at least four items. So the ul "has a 4th child" exactly when it has 4+ items. With four items the list splits into two columns (1, 2 on the left and 3, 4 on the right); with three items it stays a normal single list.
Which element gets styled?
Selector Styled element Condition
─────────────────────────── ────────────────── ─────────────────────────────────
.card img the img img is inside a .card
.card:has(img) the .card card contains an img
.card:has(> img) the .card img is a direct child
h2 + p the p p comes right after an h2
h2:has(+ p) the h2 h2 is right before a p
form:has(:invalid) button the button its form contains an invalid fieldSpecificity of :has()
Like :is() and :not(), :has() itself adds nothing; it takes the specificity of the most specific selector in its argument list.
.card:has(img) → .card (0,1,0) + img (0,0,1) = (0,1,1)
.card:has(.badge, #promo) → .card (0,1,0) + #promo (1,0,0) = (1,1,0)
a:has(> img) → a (0,0,1) + img (0,0,1) = (0,0,2)Note the second line: even when the card actually matches because of .badge, the rule still carries the ID weight of #promo.
Rules and limits of :has()
:has()cannot be nested inside another:has().Pseudo-elements such as
::beforeare not allowed inside:has().If a browser does not understand
:has(), the whole rule is thrown away (remember from CSS Selectors: one invalid selector drops the rule). Design so that the page still works without the:has()rule — treat it as an enhancement.Performance: browsers have optimised
:has()well, but very broad patterns likebody:has(*:hover)make the browser re-check a lot on every change. Anchor it to a specific component (.card:has(...)) when you can.
2. Native CSS Nesting
In a real style sheet you often repeat the same parent selector again and again:
.nav { background: #eef; padding: 8px; }
.nav a { color: darkblue; }
.nav a:hover { color: red; }
.nav.nav--dark { background: #223; }
.nav.nav--dark a { color: white; }Preprocessors like Sass solved this years ago with nesting. Now plain CSS can do it too:
.nav {
background: #eef;
padding: 8px;
a {
color: darkblue;
}
& a:hover {
color: red;
}
&.nav--dark {
background: #223;
a {
color: white;
}
}
}This compiles in your head (and in the browser) to exactly the five rules above. The grouping makes it obvious that all these rules belong to the navigation component.
The nesting selector &
Inside a nested rule,
&stands for the parent rule's selector. A nested selector without&is treated as a descendant of the parent (as if&followed by a space were written in front of it).
Written inside .nav { } | Means | Matches |
|---|---|---|
a { } | .nav a | Links inside the nav |
& a { } | .nav a | Same thing, written explicitly |
> li { } | .nav > li | Direct-child list items |
&:hover { } | .nav:hover | The nav itself while hovered |
:hover { } | .nav *:hover | Any hovered element inside the nav |
&.active { } | .nav.active | The nav when it also has class active |
.theme-alt & { } | .theme-alt .nav | The nav when inside .theme-alt |
& + & { } | .nav + .nav | A nav right after another nav |
The single most important line in that table: &:hover and :hover are different. Without the &, the browser inserts a descendant space, so :hover applies to hovered children, not to the parent itself.
& can go anywhere
Putting & at the end flips the relationship — "this component, when it sits inside something else":
.nav {
.theme-alt & {
border: 3px solid orange; /* means: .theme-alt .nav */
}
}Nesting media queries
You can also nest at-rules like @media (and @container from Container Queries). The declarations inside apply to the parent selector:
.nav {
padding: 8px;
@media (width < 600px) {
padding: 2px; /* means: @media (width < 600px) { .nav { padding: 2px; } } */
}
}Tested result: in a 504px-wide viewport the nav's padding was 2px; at 882px it was 8px. Keeping a component's responsive tweaks right next to its base styles is one of the nicest things about nesting.
Specificity: & behaves like :is()
When the parent rule has a selector list, the nested selector is treated as if the parent list were wrapped in :is(). That has a surprising effect:
#a, .b {
& span { color: purple; } /* = :is(#a, .b) span */
}
.b span { color: green; } /* comes later in the file */<div class="b"><span>Which colour am I?</span></div>Output: the span is purple, even though the green rule comes later. Why?
:is(#a, .b) span → :is() takes its MOST specific argument (#a) → (1,0,0) + span (0,0,1) = (1,0,1)
.b span → (0,1,0) + (0,0,1) = (0,1,1)
(1,0,1) beats (0,1,1), so source order never gets a chance to decide.Sass behaves differently here (it would expand to #a span, .b span), so code that moves from Sass to native nesting can change specificity. The fix is simple: don't mix IDs and classes in one parent list.
Nesting is not string concatenation
In Sass, &__title inside .card glues text together to make .card__title. Native CSS does not do this. & represents a selector, not text, so &__title is invalid and the browser silently drops that nested rule. (We'll meet names like card__title in CSS Architecture & BEM; in native CSS you write the full class name.)
.card {
&__title { color: red; } /* ❌ ignored in native CSS (works only in Sass) */
.card__title { color: red; } /* ✅ means .card .card__title */
}How deep should you nest?
Nesting makes deep selectors very easy to write — .page .main .article .card .body p a is just six levels of indentation. But deep selectors are fragile (they break when HTML moves) and high in specificity. A good rule of thumb: at most 2–3 levels, and use nesting mainly for states (&:hover), modifiers (&.is-open) and media queries.
3. min(), max() and clamp()
In CSS Units you saw calc(). These three functions are its cousins: they compare values and pick one, and they can mix units freely (%, px, rem, vw...).
min(a, b, ...)returns the smallest value.max(a, b, ...)returns the largest value.clamp(MIN, PREFERRED, MAX)returns PREFERRED, but never less than MIN and never more than MAX.
The names confuse everyone at first, so remember it this way:
min()sets a maximum limit:width: min(100%, 600px)means "fill the space, but at most 600px".max()sets a minimum limit:font-size: max(1rem, 2vw)means "2vw, but at least 1rem".clamp()sets both. In factclamp(MIN, VAL, MAX)is defined asmax(MIN, min(VAL, MAX)).
A responsive container in one line
.wrap {
width: min(100% - 2rem, 60ch);
margin-inline: auto; /* centred (logical properties are covered below) */
}Inside min() (and max()/clamp()) you can do arithmetic directly — no need to write calc(). Remember that + and - must have spaces around them.
Phone, parent 360px wide: 100% - 2rem = 360 - 32 = 328px 60ch ≈ 534px → min = 328px
Laptop, parent 1200px wide: 100% - 2rem = 1200 - 32 = 1168px 60ch ≈ 534px → min ≈ 534px(ch is the width of the "0" character in the current font, so 60ch depends on the font. In our test with a default sans-serif font at 16px, 60ch came out to about 534px.) On a phone you get a 1rem gap on each side; on a big screen the text column stops at a comfortable reading width. Before min(), this took width + max-width + padding.
Fluid typography with clamp()
.title {
font-size: clamp(1.5rem, 1rem + 2vw, 3rem);
}Let's work it out with 1rem = 16px, so MIN = 24px and MAX = 48px. Recall that 1vw is 1% of the viewport width.
| Viewport width | Preferred: 16px + 2vw | Clamped result |
|---|---|---|
| 320px | 16 + 6.4 = 22.4px | 24px (raised to MIN) |
| 400px | 16 + 8 = 24px | 24px (exactly MIN) |
| 900px | 16 + 18 = 34px | 34px (in range) |
| 1600px | 16 + 32 = 48px | 48px (exactly MAX) |
| 1920px | 16 + 38.4 = 54.4px | 48px (lowered to MAX) |
Tested in Chrome: at an 882px-wide viewport the computed size was 33.64px (16 + 0.02 × 882 = 33.64) — exactly the formula. The heading grows smoothly between 400px and 1600px screens with no media queries at all.
font-size
48px ┤ ┌──────────── capped at MAX
│ ╱
│ ╱
│ ╱ grows with 1rem + 2vw
│ ╱
24px ┤─────────────┘ floor at MIN
└─────────────┬────────────┬──────────── viewport width
400px 1600pxWhy "1rem + 2vw" and not just "4vw"?
Two reasons:
Zoom and accessibility. The user's default font-size setting changes
rem, but a purevwvalue ignores it completely, and it also scales poorly with browser zoom. Mixing in arempart keeps text responsive to the user's preferences.Gentler scaling. A rem base plus a small vw part grows more slowly than pure vw, so text doesn't jump from tiny to huge.
Other good uses
/* spacing that grows with the screen */
.section {
padding-block: clamp(2rem, 5vw, 6rem);
}
/* grid columns at least 220px, but never wider than the container */
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(220px, 100%), 1fr));
}
/* a sidebar that is 30% wide but never thinner than 200px */
.sidebar {
width: max(30%, 200px);
}The grid line is a well-known trick from Grid Layout Patterns: without the min(220px, 100%), a container narrower than 220px would overflow.
Edge case: MIN larger than MAX
If you make a mistake like clamp(3rem, 5vw, 2rem), the MIN wins, because the formula is max(MIN, min(VAL, MAX)): the inner part is at most 2rem, and then max(3rem, ...) always gives 3rem.
4. Logical Properties
Up to now we have written margin-left, padding-top, border-right... These are physical directions. They work fine for English, but not every language flows left-to-right:
Arabic, Urdu and Hebrew are written right-to-left (RTL).
Japanese, Chinese and Mongolian can be written vertically.
If you give a list item margin-left: 20px to indent it, an Urdu version of your page will have the indent on the wrong side. Logical properties fix this.
Logical properties describe directions relative to the flow of text instead of the screen. The inline axis is the direction text runs within a line; the block axis is the direction in which lines and blocks stack. Each axis has a start and an end.
English (horizontal, left-to-right) Urdu (horizontal, right-to-left)
block-start (top) block-start (top)
┌──────────┐ ┌──────────┐
inline- │ text → → │ inline- inline- │ ← ← text │ inline-
start │ text → → │ end end │ ← ← text │ start
(left) └──────────┘ (right) (left) └──────────┘ (right)
block-end (bottom) block-end (bottom)Mapping table (horizontal, left-to-right text)
| Physical property | Logical property |
|---|---|
margin-top / margin-bottom | margin-block-start / margin-block-end |
margin-left / margin-right | margin-inline-start / margin-inline-end |
| top + bottom margins together | margin-block: 10px 20px; |
| left + right margins together | margin-inline: auto; |
padding-left | padding-inline-start |
border-left | border-inline-start |
width / height | inline-size / block-size |
max-width | max-inline-size |
top / left | inset-block-start / inset-inline-start |
top: 0; right: 0; bottom: 0; left: 0; | inset: 0; (a handy shorthand, but note: with several values it uses physical top/right/bottom/left order, like margin) |
text-align: left | text-align: start |
The two-value shorthands follow the order start, end: padding-inline: 10px 20px means 10px at inline-start and 20px at inline-end. One value applies to both sides.
Worked example: the same CSS in LTR and RTL
.box {
inline-size: 300px;
margin-inline: auto;
padding-block: 10px;
padding-inline: 20px;
border-inline-start: 6px solid teal;
background: #eee;
}<div class="box">LTR box</div>
<div dir="rtl">
<div class="box">RTL box</div>
</div>Output: both boxes have a 300px-wide content area and are centred. The first box has its teal accent bar on the left and its text starts at the left. The second box, inside dir="rtl", has the teal bar on the right and its text starts at the right. We wrote the CSS once; the browser chose the physical side. In Chrome's computed styles, the first box reported border-left-width: 6px and the second border-right-width: 6px.
The direction usually comes from the HTML (<html lang="ur" dir="rtl">), not from CSS. That's the correct place for it, because direction is part of the content's meaning.
Should you always use logical properties?
Yes, for spacing and alignment that follow the text: indents, gaps between an icon and its label,
text-align, centring withmargin-inline: auto. These are free wins even on English-only sites —margin-inline: autois shorter thanmargin-left: auto; margin-right: auto;.No, for things that are truly physical: a shadow that falls down-right because the light comes from the top-left, or an arrow that must point at the right edge of the screen. Keep physical properties there.
Putting It Together
Here is a small, realistic component that uses all four features:
.card {
max-inline-size: min(100%, 28rem);
margin-inline: auto;
padding: clamp(1rem, 3vw, 2rem);
border: 1px solid #ddd;
border-radius: 12px;
h3 {
margin-block: 0 0.5rem;
font-size: clamp(1.1rem, 1rem + 1vw, 1.5rem);
}
&:has(img) {
padding-block-start: 0; /* image cards: image touches the top edge */
}
&:hover {
border-color: #888;
}
}Read it top to bottom: the card is at most 28rem wide and centred; its padding grows from 1rem to 2rem with the screen; its heading has no top margin and a 0.5rem bottom margin in any writing direction; cards that contain an image lose their top padding; and the border darkens on hover.
Common Mistakes
Thinking
:has()styles the inner element..card:has(img)styles the card. To style the image, use.card img.Writing
:hoverinstead of&:hoverin nesting. Without&it means "hovered descendant".Expecting Sass-style
&__elementto work in native CSS. It is dropped; write the full class name.Nesting too deep, creating long, high-specificity selectors that are hard to override.
Mixing up
min()andmax().min()caps the value (acts like a max-limit);max()sets a floor.Missing spaces in arithmetic:
min(100%-2rem, 600px)is invalid; write100% - 2rem.Using only
vwfor font sizes, which ignores the user's font-size preference. Combine withreminsideclamp().Setting direction in CSS (
direction: rtl) instead of using thedirattribute in HTML.
Interview / Exam Questions
1. Why is :has() often called the "parent selector"? Is that name fully accurate?
Because A:has(B) lets you style A (an ancestor) based on a descendant B, something CSS could not do before. The name is not fully accurate: :has() can also look at children only (>) or at following siblings (+, ~), so h2:has(+ p) works as a "previous sibling" selector too.
2. What is the specificity of article:has(.note, #main p)?
:has() takes the specificity of its most specific argument. .note = (0,1,0) and #main p = (1,0,1), so :has() contributes (1,0,1). Adding article (0,0,1) gives (1,0,2).
3. Inside .btn { ... }, what is the difference between &:focus and :focus?
&:focus becomes .btn:focus — the button itself when focused. :focus becomes .btn *:focus — any focused element inside the button. A nested selector without & always gets an implicit descendant combinator.
4. Compute font-size: clamp(1rem, 0.5rem + 2vw, 2rem) for viewports of 300px, 1000px and 1500px (1rem = 16px).
MIN = 16px, MAX = 32px, preferred = 8px + 2vw.
300px: 8 + 6 = 14px → below MIN → 16px
1000px: 8 + 20 = 28px → in range → 28px
1500px: 8 + 30 = 38px → above MAX → 32px
5. What does width: min(90%, 800px) give for parents of 600px and 1200px?
600px parent: 90% = 540px, compared with 800px → 540px. 1200px parent: 90% = 1080px, compared with 800px → 800px. So it is "90% of the parent, but at most 800px".
6. A page is translated to Arabic (dir="rtl"). Which of these indents still appear on the correct side: margin-left: 2rem or margin-inline-start: 2rem?
Only margin-inline-start: 2rem. In RTL, inline-start is the right side, so the indent follows the text. margin-left stays on the left, which is the end of an Arabic line.
7. Given #a, .b { & span { color: purple; } } followed by .b span { color: green; }, what colour is a span inside .b, and why?
Purple. Native nesting treats the parent list like :is(#a, .b), whose specificity is that of #a. So the nested rule is (1,0,1), which beats .b span at (0,1,1) regardless of source order.
Summary
| Feature | Example | What it solves |
|---|---|---|
:has() | .card:has(img) | Style an element based on its contents or next siblings |
| Nesting | .nav { &:hover { } a { } } | Group a component's rules without a preprocessor |
min() | width: min(100%, 600px) | Upper limit for a flexible value |
max() | width: max(30%, 200px) | Lower limit for a flexible value |
clamp() | clamp(1.5rem, 1rem + 2vw, 3rem) | Fluid sizes between two limits |
| Logical properties | margin-inline: auto | Spacing that follows text direction (LTR, RTL, vertical) |
The element before
:hasis the one styled;:has()takes its most specific argument's specificity.In nesting,
&is the parent selector; without it you get a descendant.&is not text, so no&__suffix.clamp(MIN, VAL, MAX)=max(MIN, min(VAL, MAX)); mixremwithvwfor accessible fluid type.Inline = direction of text in a line, block = direction lines stack; start/end flip automatically with
dir.
In the next chapter, CSS Architecture & BEM, we step back from individual features and look at how to organise the CSS of a whole project so that it stays maintainable as it grows.