Sometimes you need the same CSS class to behave differently depending on the HTML element it’s applied to. A common scenario: applying border-radius to cards or containers where divs need top-only rounding but articles need full rounding.
The traditional approach scatters your class definition across multiple selectors. CSS nesting gives you a cleaner solution.
The Problem
You have a class that needs different border-radius values:
- Top corners only (8px 8px 0 0) when applied to
<div> - All corners (8px) when applied to
<article>
The Solution
Use CSS nesting with the & selector to define element-specific overrides within your class:
.blog-card {
inline-size: 100%;
aspect-ratio: 16/9;
background: linear-gradient(40deg, var(--primary-dark), var(--base));
position: relative;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: clamp(3rem, calc(3rem + ((1cqw - 0.3rem) * 6.1404)), 10rem);
gap: var(--content-gap);
/* Subtiler Basisschatten */
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
article& {
border-radius: var(--radius, 0.5rem);
}
div& {
border-radius: var(--radius, 0.5rem) var(--radius, 0.5rem) 0 0;
}
}
The syntax div& compiles to div.blog-card in the final CSS, giving it higher specificity than the base .blog-card selector.
Usage
<etch:element tag={props.type} class="blog-card">
{#if props.type == "div"}
<h1 class="blog-card__heading">{props.heading}</h1>
{/if}
{#if props.type !== "div"}
<h2 class="blog-card__heading"><a href={props.link}>{props.heading}</a></h2>
{/if}
{#loop props.badge as item}
<p class="blog-card__badge">{item.name}</p>
{/loop}
<p class="blog-card__branding">{props.branding}</p>
</etch:element>
Browser Support
CSS nesting is supported in all modern browsers as of 2023. For older browser support, use a preprocessor like Sass/SCSS (the syntax is identical) or stick with traditional separate selectors.
Builder Support
I use this in Etch which supports this natively. All variables are AutomaticCSS variables.
Why This Works
The & selector references the parent selector. When you write div&, you’re saying “select a div that has this class,” not “select a div inside this class.” This keeps your element-specific variations grouped with the base class definition instead of scattered throughout your stylesheet.
One class, multiple behaviors, zero duplication.