CSS Nesting
The ampersand symbol &
- parent element
Benefits of CSS nesting
- Easier to read CSS.
- Grouping style together.
- Scoping specific styles.
- Styling HTML elements that don’t have a class or ID.
.nav__item {
& a {
display: block;
padding: 1.5rem 1rem;
}
}
/* Same as: */
.nav__item a {
}
.nav__item {
a {
display: block;
padding: 1.5rem 1rem;
}
}
/* Same as: */
.nav__item a {
}
.nav__item {
.link {
display: block;
padding: 1.5rem 1rem;
}
}
/* Same as: */
.nav__item .link {
}
.nav__item {
& + & {
border-left: 2px solid;
}
}
.nav__item {
> a {
padding: 1rem;
}
}
.nav__item {
& a {
color: blue;
}
}
button {
&:hover {
background-color: var(--bg-color);
}
&:focus {
outline: solid 2px;
}
}
.post-content {
h1,
h2,
h3,
h4 {
color: var(--heading-color);
font-weight: var(--heading-font-bold);
margin-bottom: var(--size-2);
}
}
.post-content {
:is(h1, h2, h3, h4) {
color: var(--heading-color);
font-weight: var(--heading-font-bold);
margin-bottom: var(--size-2);
}
}
.post-content {
& p {
color: var(--color-black);
& a {
font-weight: bold;
text-decoration: underline;
&:hover {
/* hover styles */
}
}
}
}
.post-content {
& p {
/* base styles */
@media (min-width: 400px) {
/* do something */
}
}
}
.post-content {
& figure {
& img {
/* the figure's image styles */
}
/* changes to the <figure> container, if it has a figcaption element */
&:has(figcaption) {
display: flex;
align-items: start;
}
& figcaption {
/* caption styling */
}
}
}
.post-content {
li {
&:not(:last-child) {
border-bottom: 1px solid;
}
}
}
.post-content {
& h3 + [class*="language-"],
& h4 + [class*="language-"] {
margin-top: 0.5rem;
}
}
.card__content {
& h3 + p {
border-top: 1px solid #000;
padding-top: 0.5rem;
margin-top: 0.5rem;
}
@container card (min-width: 400px) {
display: flex;
flex-direction: column;
justify-content: center;
}
}
.card {
& * {
/* styles here */
}
}
.card {
&[data-type="featured"] {
/* styles here */
}
}