Math, Nesting, and Layers Preview
CSS has grown well beyond simply assigning static values to properties. Modern browsers understand math functions that let you calculate sizes, clamp values between limits, and pick the smallest or largest from a set of candidates. On top of that, native CSS nesting now lets you structure your stylesheets in a way that mirrors your HTML, keeping related rules together instead of scattering them across the file. Finally, two organizational features, @import and @layer, give you control over how your files are split and how the cascade resolves conflicts.
This page walks through each of these topics. By the end you will be comfortable using calc(), min(), max(), and clamp() for fluid layouts, writing nested CSS that takes advantage of the updated specification, and understanding how @import and @layer fit into a well organized project.
CSS Math Functions
You have already seen var() pull values from custom properties. Math functions take things further by letting you compute values on the fly, right inside your CSS. These are not preprocessor tricks that disappear at compile time. The browser evaluates them at runtime, which means they can respond to the viewport, the parent container, and the current value of any custom property.
calc()
The calc() function performs addition, subtraction, multiplication, and division. Its most useful ability is mixing units that you could never combine otherwise. Want a width that is "100% of the container minus 24 pixels of padding"? That is exactly what calc() is for.
.sidebar {
width: calc(100% - 24rem);
}
.card {
padding: calc(var(--space-md) * 2);
margin-bottom: calc(var(--space-md) + 0.5rem);
}
Notice that you can use custom properties inside calc(). This is where the design tokens you learned about on the Custom Properties page start to pay off. Instead of hard coding a padding value, you derive it from a token, and if the token changes, every derived value updates with it.
Addition (+) and subtraction (-) require a space on both sides of the operator. Multiplication (*) and division (/) do not, but adding spaces makes your code easier to read. If you forget the spaces around + or -, the browser will silently ignore the entire declaration.
min() and max()
The min() function returns the smallest value from a list. The max() function returns the largest. They accept any number of comma separated values, and those values can mix units freely.
.container {
/* Never wider than 120rem, but shrinks with the viewport */
width: min(100%, 120rem);
margin-inline: auto;
}
.hero-image {
/* At least 30rem tall, but grows with the viewport */
height: max(30rem, 50vh);
}
A helpful way to remember which one to use: min() sets an effective maximum (the value will never exceed the smallest candidate), and max() sets an effective minimum (the value will never drop below the largest candidate). That sounds backwards at first, but once you see it in action a few times it becomes intuitive.
clamp()
The clamp() function combines min() and max() into a single expression. It takes three arguments: a minimum, a preferred value, and a maximum. The browser uses the preferred value as long as it stays within the bounds. If it drops below the minimum, the minimum wins. If it exceeds the maximum, the maximum wins.
h1 {
/* Grows with the viewport, but never smaller than 2.4rem
or larger than 4.8rem */
font-size: clamp(2.4rem, 5vw, 4.8rem);
}
.section {
padding: clamp(1.6rem, 4vw, 4rem);
}
This is the foundation of fluid typography and fluid spacing. Instead of writing media queries for every breakpoint, you let clamp() scale values smoothly across all viewport sizes. The result is a design that feels natural on every screen without a single breakpoint. Think of it like the difference between a dimmer switch and a light switch. A media query flips between two states; clamp() transitions smoothly across a range.
Under the hood, clamp(MIN, PREFERRED, MAX) is the same as max(MIN, min(PREFERRED, MAX)). The preferred value is allowed to float, then min() caps it at the maximum and max() lifts it to the minimum. That is why min() often feels like setting a maximum width and max() often feels like setting a minimum height.
Seeing Clamp Decide
Fluid sizing often uses a preferred value tied to the screen, such as 40vw. The unit vw means viewport width: 1vw is 1% of the browser window width, so 40vw is 40% of the window. That is different from %, which is usually 40% of the parent element, not the window. In real layouts those can disagree when the parent is narrower than the page. This demo lets you switch the preferred unit while you watch clamp() choose Minimum, Preferred, or Maximum.
The outer box is a stand-in for either the viewport (when Preferred uses vw) or the parent container (when Preferred uses %). The colored bar is the element. You are not trying to fill the box to the right edge. Empty space on the right when Maximum wins is the ceiling doing its job.
width: clamp(80px, 40vw, 180px)
Final element width: 112px (Preferred).
Switch Preferred Unit between Viewport (vw) and Parent (%) and read the explanation under the box. Then drag Box Width wider until Maximum wins and notice the gap on the right: that gap is intentional. Drag narrower until Minimum wins and the element refuses to shrink below 80px.
Fluid Sizing Demo
The decision demo above shows the numbers. This card shows the design pay off. Resize your browser window and watch the type and padding scale between their clamp() bounds without media queries.
Fluid Typography Example
This heading and paragraph both use clamp() for their font sizes, and the padding around them uses clamp() too. No media queries involved. Narrow your browser window and watch everything scale smoothly.
clamp(2rem, 4vw, 3.2rem) · Body: clamp(1.6rem, 2.5vw, 2rem) · Padding: clamp(1.6rem, 4vw, 4rem)
Native CSS Nesting
If you have used Sass or LESS, nesting will feel familiar. You write child rules inside their parent rule, and the browser figures out the full selector. What used to require a preprocessor is now part of the CSS language itself. The big advantage is that your stylesheet can mirror the structure of your HTML, making it easier to see which styles belong to which part of the page.
Basic Nesting
Here is a common pattern: a .card component with a heading, paragraph, and link inside it. Without nesting, you write each selector separately. With nesting, you group them together.
/* Without nesting */
.card {
padding: var(--space-md);
border-radius: var(--radius);
}
.card h2 {
font-size: var(--text-xl);
margin-bottom: var(--space-sm);
}
.card p {
color: var(--color-text-muted);
}
.card a {
color: var(--color-link);
}
.card a:hover {
color: var(--color-link-hover);
}
/* With nesting */
.card {
padding: var(--space-md);
border-radius: var(--radius);
h2 {
font-size: var(--text-xl);
margin-bottom: var(--space-sm);
}
p {
color: var(--color-text-muted);
}
a {
color: var(--color-link);
&:hover {
color: var(--color-link-hover);
}
}
}
Notice that h2, p, and a are written without the & symbol. The updated CSS nesting specification does not require & for descendant selectors. The browser automatically prepends the parent selector with a space, so h2 inside .card becomes .card h2. This is different from early tutorials and videos you might find online (including this excellent Kevin Powell walkthrough) that show & used on every nested rule. The spec has been relaxed since those were recorded. You only need & in specific situations, which we will cover next.
When You Need the Ampersand (&)
The & nesting selector is required in three situations. Understanding when to use it and when to leave it out is the key to writing clean, modern nested CSS.
Pseudo classes and pseudo elements. When you attach something directly to the parent selector like :hover, :focus, ::before, or ::after, you need & so the browser knows there is no space between the parent and the pseudo selector. Without it, :hover inside .card would become .card *:hover (targeting any hovered descendant), not .card:hover.
.btn {
background-color: var(--color-primary);
/* Correct: & attaches :hover directly to .btn */
&:hover {
background-color: var(--color-primary-hover);
}
/* Correct: & attaches ::after directly to .btn */
&::after {
content: ' →';
}
}
Compound selectors. When you need to combine the parent with another class, an attribute, or an ID without a space, & is required. The classic example is modifier classes.
.card {
background-color: var(--card-bg);
/* .card.featured (no space = compound selector) */
&.featured {
border-left: 4px solid var(--color-accent);
}
/* .card[data-size="large"] */
&[data-size="large"] {
padding: var(--space-xl);
}
}
Reversing context. You can place & after another selector to reverse the nesting direction. This is useful when a parent context should change a child component.
.card {
background-color: var(--card-bg);
/* When .card is inside .sidebar, reduce padding */
.sidebar & {
padding: var(--space-sm);
}
}
/* This compiles to: .sidebar .card { padding: var(--space-sm); } */
Nesting Media Queries
One of the most satisfying uses of nesting is placing media queries right next to the rules they modify. Instead of scrolling to the bottom of your file to find a breakpoint block, you keep the responsive adjustment inside the component it affects.
.grid {
display: grid;
grid-template-columns: 1fr;
gap: var(--space-md);
@media (width >= 768px) {
grid-template-columns: repeat(2, 1fr);
}
@media (width >= 1024px) {
grid-template-columns: repeat(3, 1fr);
}
}
The browser expands this into the traditional separate @media blocks you are used to, but your source code stays organized by component rather than by breakpoint. This is the same pattern that made Sass nesting popular, and now it works natively.
How Nesting Mirrors HTML
Think of your HTML as the blueprint for a chapel building. The building has a main hall, the hall has pews, and each pew has hymnals. Your nested CSS can follow that same hierarchy. The .chapel rule contains the .hall rule, which contains the .pew rule. When you read the CSS, you can see the structure of the page without switching to the HTML file.
.chapel {
max-width: 120rem;
margin-inline: auto;
.hall {
padding: var(--space-lg);
.pew {
display: flex;
align-items: center;
gap: var(--space-sm);
.hymnal {
font-size: var(--text-sm);
color: var(--color-text-muted);
}
}
}
}
A word of caution: just because you can nest deeply does not mean you should. Two or three levels is usually the sweet spot. Beyond that, your selectors become overly specific, which makes them harder to override later. If you find yourself nesting four or five levels deep, it is usually a sign that your HTML or your component boundaries could be simplified.
Every level of nesting adds specificity. A rule like .chapel .hall .pew .hymnal has a specificity of 0,4,0, which makes it difficult to override without resorting to even longer selectors or !important. Keep your nesting shallow to keep your specificity manageable.
For a thorough reference on every edge case, the MDN guide on CSS nesting covers compound selectors, nested at-rules, and the specificity implications in detail.
Organizing Files with @import and @layer
As your projects grow, a single CSS file becomes difficult to manage. You end up scrolling past hundreds of lines to find the rule you need. The solution is to split your CSS into multiple files, each with a clear responsibility: one for tokens, one for base styles, one for components, and so on. Two CSS features make this possible: @import for pulling files together and @layer for controlling how they interact with the cascade.
@import: Bringing Files Together
The @import rule loads one CSS file into another. You have probably seen this before, but in modern projects it serves a specific organizational purpose. Your main stylesheet becomes a table of contents that imports everything else.
/* main.css */
@import 'tokens.css';
@import 'reset.css';
@import 'base.css';
@import 'components.css';
@import 'utilities.css';
Each file handles one concern. tokens.css defines your custom properties. reset.css normalizes browser defaults. base.css styles raw HTML elements. components.css styles your reusable pieces. utilities.css provides helper classes. When you need to change a token, you open one file. When you need to tweak a component, you open another. Nobody has to wade through everything at once.
@layer: Controlling Cascade Order
Splitting files solves the organization problem, but it introduces a new question: what happens when two files define conflicting rules? Normally, CSS resolves conflicts by source order (the last rule wins) and specificity (the most specific selector wins). @layer gives you a third lever. You declare named layers in the order you want them to apply, and the browser respects that order regardless of where the actual rules appear in the file.
/* Declare layer order up front */
@layer reset, base, components, utilities;
@import 'reset.css' layer(reset);
@import 'base.css' layer(base);
@import 'components.css' layer(components);
@import 'utilities.css' layer(utilities);
With this setup, a utility class will always beat a component style, and a component style will always beat a base style, regardless of specificity. This eliminates the common frustration of writing a utility class like .text-center and having it lose to a more specific component rule. The layer order settles the dispute.
This is a conceptual introduction. Unit 2 covers @layer in depth with the Cascade Layers learning activity, where you will practice creating and ordering layers in real projects. For now, the important idea is that @import splits your code into files and @layer controls how those files interact with the cascade.
See It on This Course Site
This very course site uses the @import and @layer pattern described above. If you open your browser DevTools on any page and look at the stylesheet, you will see tokens, base styles, components, and utilities organized into separate imported files assigned to named layers. It is a real world example of the pattern at a modest scale. As you work through the course, pay attention to how the site's CSS is structured. It is designed to be a living reference you can study alongside the material.
Putting the Pieces Together
The three topics on this page work together. Math functions let you derive flexible values from your design tokens. Nesting lets you organize rules in a way that mirrors your HTML structure. And @import with @layer lets you split those organized rules into separate files with predictable cascade behavior. Together they form the foundation of a modern CSS workflow: tokens define your decisions, math functions make those decisions responsive, nesting keeps your rules readable, and layers keep the cascade under control.
In your upcoming assignments you will put these ideas into practice. Start paying attention to opportunities where clamp() can replace a media query, where nesting can group related styles, and where splitting a file would make your project easier to navigate. These habits compound over time and become the difference between a stylesheet that fights you and one that works with you.
Check Your Understanding
A student just completed a learning activity covering CSS math functions (calc, min, max, clamp), native CSS nesting with the updated spec, and a conceptual introduction to @import and @layer. They learned that clamp() takes a minimum, preferred, and maximum value for fluid sizing, that native nesting no longer requires the ampersand for descendant selectors, that the ampersand is only needed for pseudo classes, compound selectors, and reversing context, and that nesting media queries inside a rule keeps responsive adjustments co-located with the component.\n They are working on writing nested CSS for a .testimony-card component with fluid sizing using clamp(). Review their code and give direct feedback. Tell them what they did well and where they need to improve. Check that they used clamp() correctly with three arguments for at least one property, nested descendant selectors without unnecessary ampersands, used the ampersand correctly for pseudo classes like :hover, and kept nesting to a reasonable depth. Watch for common mistakes like using the ampersand on every nested rule (old spec habit), forgetting spaces around + and - in calc(), nesting too deeply, or using clamp() with only two arguments. Guide them back to the concepts rather than providing complete solutions.
/**
* Create a .testimony-card component using nested CSS.
*
* 1. Use clamp() for padding that scales fluidly
* between a minimum and maximum.
*
* 2. Nest the h3, p, and a selectors inside
* .testimony-card WITHOUT using & (they are
* descendants, not compound selectors).
*
* 3. Use & correctly for the a:hover pseudo class.
*
* 4. Add a nested @media query that changes the
* layout at a wider viewport.
*/
.testimony-card {
/* Your fluid padding here. */
h3 {
/* Heading styles here. */
}
p {
/* Paragraph styles here. */
}
a {
/* Link styles here. */
/* Add :hover with proper & usage. */
}
/* Add a nested @media query here. */
}