Game Changing CSS Trick (for Noobs Like Me)
OK, I just learned a brilliant CSS technique I wish I knew about much sooner! This is probably old news for most of you wizards out there - but maybe this little post can be useful for some fellow newbies?
This is one of my "Noob teaching noobs" posts. Some experts are excellent teachers - but not all. Hopefully, these posts can be helpful due to their layman nature, but please contact me if I'm misinforming!
Here are some examples of selectors I could see myself using:
h1 {}
-> Styling Header 1 (h1) elements.
h1:hover {}
-> Style when hovering h1.
h1::after {}
-> A pseudo-element (like a line) related to h1.
h1:hover::after {}
-> The pseudo-element when I hover over h1.
h1 a {}
-> A link (a) within an h1 element.
h1 a:hover {}
-> When I hover over one of those links.
.page-content h1:hover {}
-> When I hover an h1 that’s within .page-content.
Put into context, I could do:
h1 { color: var(–header-color); }
h1 a {
color: (--link-color);
}
Having them separate like this isn’t a big deal - but it gets more messy if I want to style all the header levels:
h1,
h2,
h3,
h4,
h5,
h6 {
color:black;
}
h1 a,
h2 a,
h3 a,
h4 a,
h5 a,
h6 a {
color:blue;
}
Now, imagine doing this again for all the variants I showed in the beginning!
I just learned you could instead do this instead:
h1,
h2,
h3,
h4,
h5,
h6 {
color:black;
a {
color: blue;
}
}
Nice! Saves some space. But the really useful thing I learned, was that you can use &
as a substitute for every element mentioned up top. So we could, for instance, adjust the :hover styling for both the headers themselves and when hovering links within any of the headers:
h1,
h2,
h3,
h4,
h5,
h6 {
color: var(--header-color);
a {
color: var(--link-color);
&:hover {
color: var(--link-hover-color)
}
}
&:hover {
color: var(--header-hover-color)
}
}
Notice that the first &
is substituting a
, and the second is substituting all the headers.
Lastly, I could also do the following, to select “the ::after element for all headers - but only when the heading is inside a .page-content”:
h1,
h2,
h3,
h4,
h5,
h6 {
color: var(--heading-color);
.page-content &::after {
color: var(--heading-after-color);
}
}
To be honest, I knew about the nesting previously - but I just didn’t bother, as I didn’t see that much use in it for me. But combined with the &
, it’s a game changer for me!
I’ll leave you with a little assignment:
Try to parse this real example from my website’s CSS. 👇🏻 It’s not a sensible way to use this feature - as it doesn’t save any space or make it easier in any way! But it’s what it looks like when someone who just learned something new tries to learn. 😁
a.read-more {
animation: unset;
&::after {
content: none;
}
p:has(&) {
margin-top: var(--padding-block);
}
@media (hover: hover) {
&:hover {
filter: var(--drop-shadow-icon-hover);
}
}
}