Getting started with CSS Nesting
Skills:
Prompt Craft60%
Key Takeaways
The video covers CSS Nesting, a feature that allows for more concise and readable CSS code, and demonstrates its usage with various tools and techniques, including the ampersand (&) and media queries.
Full Transcript
Hello, my friend and friend, and welcome back to the channel. If you're new here, my name is Kevin, and here at my channel, I help people fall in love with CSS. And one awesome feature that can help do that is nesting. Now, really importantly, not everyone loves nesting, and there's a few reasons for that that we'll talk about as we go through this video, but there's one use case that I think everybody can get on board with. But before we get to that, let's cover the absolute uh basics of it to understand even what CSS nesting is and how it works, uh and then we'll get into the the the best use cases for it, at least in my own opinion. So, uh you can see here I have this category set up with a categories A to select the links that are in my categories. And if we go look at my HTML, this is my UL here. I have some list items with links inside of there. So, just like in my HTML, these links are nested inside of my UL. That means I can use CSS nesting. And basically, anytime you have a descendant selector, you can use it. So, there's use case number one. Some people will tell you not to use descendant selectors, that everything should be uh have its own class. I firmly disagree with that, but uh if that's the method that you're using, then nesting might not be for you. But we're going to look at how we can do this cuz you'll probably come across it uh a bit more commonly now that it is part of CSS and well supported. Uh and basically, it's when we have a descendant here, instead of having it floating out here or having to repeat the parent here and here, I can just come in and put those styles here instead. So, again, nested my A inside my UL. Same thing. My A is now listed inside of the categories uh selector here. And that means let's just take all of this, comment it out, hit save, so the styling goes back to the default links, and we can bring all of this into the nested selector here instead. Fix my formatting a little bit. Hit save, and now it goes back to what we had previously. So, a good start. Uh we do want to add a hover and focus state to these. I think that's important. But uh what I also want to look at is how we can use combinators. So, this is an interesting combinator, the the plus one. And what that's doing is selecting the image that comes directly after my categories here. So, if I'm always having this pattern, I want this image to have some certain styles on it that I've put right here. Again, anytime we have a descendant, that means we can use nesting if we'd rather. So, I'm going to select all of this, copy, comment it out, so it breaks my image styling, and then over here, where I have my categories, I can come in here, paste that in, and we wanted a plus IMG. We can do it exactly the same way. So, plus IMG, the selector stays the same. So, the selector that we had before is exactly the same. We just don't include the categories part before it, so whatever the first part of the selector was. Uh and then we still have the opening closing curly braces. All of that stays the same. And then we have our uh our styles that come right in there. And it fixes it, and everything is working just fine once again. Now, if you've never seen the the plus combinator before, I have recently put a video out looking at the different combinators. Uh the plus one is in the next sibling. So, in this case, the image that comes after that. If you'd like to learn more about combinators, we have some funky ones like this, uh and the one that most people know is the direct uh child selector. So, uh you can I'll put a link in the description. Maybe there's a card popping up if you want to know more about those. But uh before you run off and go watch that, I won't put a card so you don't leave right away. We'll watch this, and at the end I'll remind you about that video. >> [laughter] >> So, let's Yeah, with this, that works really well. Uh really fast, if I came here and I added a uh direct child, that would actually break the styling of these because my links aren't direct children. I'm saying direct children. They're just not children of the UL. Uh the LIs are the children. So, this means my A is not a child of categories, so this is no longer working. If this is on my LI, it would work. And now we get some of the styling back, but the text decoration uh is still an issue. So, we'll switch this back to the A right there. Now, with this, these are links, and we don't have any hover on them, which is bad. Every anything that's interactive, we should have multiple ways of of letting the user know they can actually interact with it. So, if you've done link stuff before, you've probably done an A hover and an A focus, something like that. Uh and once again, we can use nesting. But really importantly, we cannot come, and I'm going to do it here. This is I will say one really important thing is don't nest too deep. The same way, if you're going to use descendant selectors, don't go too many levels deep because it just makes it hard to read at one point. Uh here I'm sort of just keeping all of my categories styling all together within one selector, which I find convenient. But like here, I wouldn't come in uh and before we get to the hover and focus, I wouldn't do like a uh LI and then put the A here and have all of these levels. Like we're actually increasing specificity for no reason, uh which I'll talk a bit about cuz there are some things with specificity and uh nesting that are important to know about. Uh but it also just like eventually, it gets harder to read. It gets a little bit messy. The one time I will definitely nest more than just one level deep is when it comes to using pseudo classes or pseudo elements. So, here on the A, what I can do is we want to add a hover, and the first thing you'd probably try is saying hover. And let's just say the background is going to be I have a purple color here, which is my color accent 400, I think. Uh so, if I try using that now, and we come in here, we can see nothing is actually changing. I think that's the correct name of my color, so it will change. Uh we could even just change this to red for now. So, just so you can see that it doesn't actually change when I hover on there. And that's because when we nest, we're looking for descendants. So, that would actually be the same thing as writing categories A hover with a space here. So, we'd be looking at something hovering inside the link, not on the link itself. We want to remove this space right here in our nesting. So, how do we do that? We have to use a special character. So, let's move all the way back up, right here where I had the hover, and that special character is the ampersand, just like that. Let's hit save, and we can see the red is coming on there. Does not look very nice, so let me just switch that quickly back to my uh accent 400. I think we'll look okay. We might have to change Oh, it's still red. Uh I wanted the purple, which would be my secondary. There we go. Sort of goes with the purple that we have up here. Uh and then I think the color here I can do my var color neutral 900 would probably be black. There we go. And I think that looks a little bit nicer. Uh we'd probably change the border color, do a little bit more on these, but that's fine for for our purposes right now. Uh I might even darken this a little bit. Or lighten it, I should say. There we go. I think that's even better. Perfect. So, uh one thing that's really important here is I'm doing my hover. If I wanted, we'd probably want a focus on there as well. So, I can just put my comma and do my focus. So, it'd be focus. I'm actually going to do a focus visible. On a link, it doesn't really matter one way or the other, but I tend to use focus visible for everything now. If you've never heard of focus visible, once again, I have videos on that uh or a video on the differences between them, and I'll link it down in the description and remind you about it at the end as well. Now, I mentioned this ampersand as I sort of said, you just throw one here, and and nonchalantly was going on. Uh I do we we do need to address this guy, though, cuz there's a few important things with it. First of all, uh at one point in the spec, every descendant had to start with a special character or character I I don't know if they're special characters with something like an ampersand. Uh so, if you had a combinator, you could start your nested selectors with the combinator, like I'm doing here for my image. But another thing you would also see is every single nested selector would look like this. Because that would be the placeholder for the categories, right? So, we'd be doing categories A here. Uh and eventually, they found out a way to do it without having to do that. It was a limitation the browsers had. They found a solution to it, and it was kind of annoying, so they removed that. We we can just do it like this, which is much simpler, uh but it you could do this if you wanted to. There's no problem. Just like down here, I could come in and do something like that, and that would work completely fine. But and if anybody's coming here from like preprocessors, you might not be I don't think there'll be too many people. And if you don't know what a preprocessor is, SAS is one of them, but don't worry about it too much. It's beyond the scope of this video. But I do just want to quickly mention that the ampersand does not work the same way as the ampersand did in preprocessors. So, if you're familiar with it, keep watching cuz there are some differences that will come up. And even if you're not familiar with what a preprocessor is, we're going to be talking about the important things with this ampersand cuz it's kind of funky how it works. Once you know what it's doing, you're you're good. Cuz I'm I'm saying it's a placeholder for categories, which it essentially is, but it works using another CSS feature. And what that is uh is I'm saying the word is, it happens to be the is in CSS. So, before I mentioned that when we nest, it's the same thing as writing it this way. It's not quite right. It's actually the same as writing it like this. Is categories. And at a very basic level, doesn't change anything. Is and without is in this case would be exactly the same thing. So, we're not changing much if you're using it in basic settings like this. If you've never seen is before, what is allows us to do is select multiple things. So, I've actually uh come down. Let's come here where I have my main title and the lead, and in both of them uh we have a span that has a font weight of 900. So, if we come and take a look in my index, we can see my H1 has a main title ID on there with a span inside of it. So, that's why the CSS nesting at the top is really bold. And then I have a lead paragraph down here with a span as well, which is this paragraph here, which is also coming in and is really bold. Now, the reason I'm mentioning this is to talk a little bit about is quickly where we can say is main title, {comma} {dot} lead. And I could say something like let's just say font-family is a serif. And you can see that the this is all changed cuz that's my main title. And we can see over here the lead paragraph has changed to a serif font, whereas these other ones haven't changed. What's really important and the big difference here between saying main title, {comma} lead and using our is selector, cuz we're essentially like if I did this and I did this here, they're essentially the same thing in terms of what they're accomplishing. But there's one important difference is this is two separate selectors. I have my main title ID selector and I have a class selector here. Because we have a comma between them, those are actually separate selectors, each one with its own specificity. When we write it out this way, the is is one single selector where they has a whole bunch of stuff in it, but it's treated as a single selector and the specificity that comes with that is based on the highest element included in that entire list. What does that mean? Why is this important? Uh as long as you're being smart about how you're using nesting, I don't think you'll ever run into this issue. This is a bit of a convoluted example that I came up with down here. But what I want to do is just to look here. If I did a main title, lead, span, font-weight is 900. And then I came down here and I said my lead span, without nesting, doesn't matter if I use nesting or not uh and I say the font weight is actually going to be 100. Again, this is a convoluted example uh just to show you the problems you could potentially run into. Uh cuz we can see that this isn't changing. And it looks like the specificity here would be lead span. And here I have a lead span, so they should have the same specificity. And the font weight here should then win because order would come into it. But we can actually see in our dev tools, if I do an inspect on there, on the span, the 100 is being crossed off because if I hover there, the specificity is 011. And if I come up to the font weight on this one, the specificity is 101 because that ID is contributing to the specificity of my nested selector. Don't write weird CSS and you probably won't run into issues with this. But [laughter] it could potentially be one of those things that every now and then comes to bite you. So, just if you are creating comma-separated lists and using nesting, there's the potential that some weird stuff can happen like this. I don't tend to use a lot of comma-separated lists anyway. Uh so, it hasn't really been something that has come up too often for me as an issue that I I run into. But just to throw it out there to be careful with it. Now, there's one last really important thing uh and then we'll get to that use case that is my absolute favorite use case uh for using nesting. But before we do that, I want to get to the the other thing with it, which is the order that we're putting things in. And this is where one of the big differences comes from preprocessors. And I want to mention it even if you've never used one cuz you'll probably come across at one point or another people using nesting in a very specific way. And to highlight that, we're going to come up here and I'm going to take a popular naming convention where on these links, instead of calling them categories, I'm going to give these a class of categories link. And this is a BEM naming convention that's right here that is very common and with preprocessors like Sass, it made styling these very easy. Because in Sass, what we would do is instead of having just the link like this, it's this idea that everything should just be a single class rather than using descendant selectors. You might see people writing nesting like this, categories. You'll even see the syntax highlighting is not too happy with it. But if I save that, you can notice that the styling is all broken. With preprocessors, which are things that allowed nesting before nesting was actually in the spec, what it would do is it would take someone doing this and it would replace this with the string that's here, which just meant in the final CSS, that would be closed and then you'd get a categories Oh, I just realized I did categories here. This should be link. I'm getting too into the There we go. Too into the word categories there. So, and link. And that placeholder, as I said, once the CSS would get finished, would turn into categories link this way. But this is where the important thing with the ampersand comes in. This does not work in native CSS because this ampersand isn't this exact string. This ampersand is Let's close this off. Is this. Is {dot} categories. And as you can see here, that doesn't really make any sense. Right? [laughter] The the connecting it like that uh just it it doesn't work. So, uh that is why we can't do it like that in native CSS. So, we can't create uh descendant or not descendant selectors. I don't block element modifier. You can't, you know, extend even if I did it like this way and I I called it categories link, something like that, and then I came here and I did categories link like this This doesn't work because this doesn't make any sense. If you saw this in your CSS, you go, "I don't understand what they're trying to do." That's the same thing if we had nesting and I did this. It also doesn't make any sense cuz they're actually the equivalent. So, just one of those ways that you might come across older articles talking about nesting or other examples using nesting because they were using Sass or some other sort of preprocessor where they were creating concatenated strings like that. We cannot do that with native CSS. Okay, that that's like the big one that I think people might run into. Uh but now my favorite use case of nesting. Uh and this is You might be looking at this go, "I don't want to use descendant selectors." Don't use them. That's fine. Uh you know, this is a bit of a stylistic choice. I will say actually really fast, you'll hear some people saying they don't like nesting cuz of the searchability of it. Uh because what would happen is you could look in your dev tools and in the old days, everything would be compiled from the preprocessors and all of this. Uh these days, if we come and take a look at the styles in here, let's go grab these links. This is actually like the finished the categories A. This is nested here. This is exactly the style that's in my style sheet. There's no compiling, there's no differences, so searchability is no longer an issue. Uh and for me, readability is pretty straightforward, categories A. I'm pretty happy with that. So, as far as the searchability and findability of things, I don't think that's an issue either, but it is some one of the complaints people will have about nesting that I think with native CSS is no longer an issue. And a little jump in my code here just cuz I had to re-record this part cuz I I ran into some recording issues with my files. So, uh but everything will be exactly the same and I ended up reusing this file for something a a demo that we're doing for next week's video. Uh but the first thing is here at the exact same code I had. I have my H1 that's right here and an after. So, before we get to my favorite thing, let's just fix this with some nesting where we don't have to do this and repeat the selector. I can just come here and do the ampersand instead. Hit uh and we need a second set of closing brackets for that. And I can hit save and everything is exactly the same. And now we can get to my favorite thing, which is to do with the font size that I currently have on here, which is right now. I'm going to put it here. Uh font size is 5.5 rem. I had this with some of the general styling that we had a little bit lower down. But I might not want this to be always the font size, right? If we get to two different screen sizes. If I open up my dev tools, I click this little guy that's here. People always ask me, "How do I do the responsive mode?" It's this little icony thing here. Uh and then I can come here and I can change the size. And at smaller sizes, this is really, really a big font size. I probably don't want it to be that big. So, what can we do? Well, what we usually do is have a media query and we can nest media queries, which this is my favorite thing in the world. And so, I only want this at larger sizes. So, maybe at this smaller screen size, I want like a 3.5, let's say. Uh so, there we have the smaller font size. And when we get up to maybe about, I don't know, 860 pixels, I want it to go to the larger size. So, I can just come right here and say at media width is greater and I'm going to use the range syntax, so I can use the greater than symbol, 960 pixels. And now my font size will be 5.5 rem like we had before. And we can see that working right there. And I love not having to re-declare selectors inside of the media queries. For me, this is such a big win uh for a few reasons. First of all, it keeps all the styling of this thing together instead of having it in a separate block somewhere else, even if that block is like right after here. It's a so convenient having it all together in one spot. And some people might ask, "Well, Kevin, won't this result in having multiple media queries over and over again cuz you're using the same breakpoints?" And yes, it will and no, that doesn't matter at all. When your website is online, the server hosting it is probably going to be doing some sort of compression on its own to your files. Usually, it's a gzip that it's going to be doing And GZip with is like really good at optimizing repeated code. You can have a million of the same media query and it's barely going to bloat the size of the file that's getting downloaded by the end user. I've done tests on this multiple times and yeah, it won't have any noticeable impact at all if you do have repeated media queries and just keeping them within the selector. I love it. I do this for everything now and I'm just so happy. If if we could do nothing else but just this with nesting and I'd be happy. But we have a lot of other cool things as well. Some of them more tricky ones that I'm going to be sharing next week which is I talked about I said I did a bit more of another demo and it's looking at some more advanced tips and tricks that we can do with nesting. So that video is going to be out in a week from now. If you don't want to miss that and you're not already subscribed, maybe do consider subscribing so you do know about that one. And with that I'd like to thank my enabler of awesome Johnny as well as all my other patrons and channel members for their monthly support. And of course, until next time, don't forget to make your corner of the internet just a little bit more awesome.
Original Description
CSS Nesting is awesome, though there are a few important things to know about it, which I break down in this video.
- Combinators video: https://youtu.be/rndMS4pEKP8
- Focus-visible: https://youtu.be/apdD69J4bEc
✉ Keep up to date with everything I'm up to https://www.kevinpowell.co/newsletter
💬 Come hang out with other devs in my Discord Community https://discord.gg/nTYCvrK
⭐ Are you a beginner? HTML & CSS for absolute beginners is for you: https://learn.kevinpowell.co
🎓 Start writing CSS with confidence with CSS Demystified: [https://cssdemystified.com](https://cssdemystified.com/)
🚀 Already mastered CSS? Check out my advanced course, Beyond CSS: https://www.beyondcss.dev/
⌚ Timestamps
00:00 - Introduction
00:30 - The basics of nesting
04:45 - Don’t over nest
05:30 - The & character (ampersand)
08:55 - How & works behind the scenes and a potential problem you could run into
13:45 - It doesn’t work with BEM
16:45 - Searchability isn’t an issue
17:40 - My favorite use case
#css
---
Help support my channel
👨🎓 Get a course: https://www.kevinpowell.co/courses
👕 Buy a shirt: https://cottonbureau.com/people/kevin-powell
💖 Support me on Patreon: https://www.patreon.com/kevinpowell or through YT memberships: https://youtube.com/@KevinPowell/join
---
🧑💻 My editor: VS Code - https://code.visualstudio.com/
🌈 My theme: One Dark Pro Var Night
🔤 My font: Cascadia Code
---
I'm on some other places on the internet too!
If you'd like a behind the scenes and previews of what's coming up on my YouTube channel:
Bluesky: https://bsky.app/profile/kevinpowell.co
Codepen: https://codepen.io/kevinpowell/
Github: https://github.com/kevin-powell
---
And whatever you do, don't forget to keep on making your corner of the internet just a little bit more awesome!
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Kevin Powell · Kevin Powell · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
How to create an awesome navigation bar with HTML & CSS
Kevin Powell
Improve your CSS by Keepin' it DRY
Kevin Powell
HTML & CSS for Beginners Part 6: Images
Kevin Powell
HTML & CSS for Beginners Part 7: File Structure
Kevin Powell
HTML & CSS for Beginners Part 4: Bold and Italic text and HTML comments
Kevin Powell
HTML & CSS for Beginners Part 5: Links
Kevin Powell
HTML & CSS for Beginners Part 3: Paragraphs and Headings
Kevin Powell
HTML and CSS for Beginners Part 1: Introduction to HTML
Kevin Powell
HTML and CSS for Beginners Part 2: Building your first web page!
Kevin Powell
HTML & CSS for Beginner Part 8: Introduction to CSS
Kevin Powell
HTML & CSS for Beginners Part 9: External CSS
Kevin Powell
HTML & CSS for Beginners Part 10: Divs & Spans
Kevin Powell
HTML & CSS for Beginners Part 11: Classes & IDs
Kevin Powell
HTML & CSS for Beginners Part 12: The CSS Box Model - Margin, Borders & Padding explained
Kevin Powell
HTML & CSS for Beginners Part 13: Background Images
Kevin Powell
HTML & CSS for Beginners Part 14: Style Text with CSS
Kevin Powell
HTML & CSS for Beginners Part 15: How to style links
Kevin Powell
HTML & CSS for Beginners Part 16: CSS selectors and Specificity
Kevin Powell
HTML & CSS for Beginners Part 17: How to Create and Style HTML Lists
Kevin Powell
HTML & CSS for Beginners Part 18: How Floats and Clears work
Kevin Powell
HTML & CSS for Beginners Part 19: Colors with CSS - hex, rgba, and hsla
Kevin Powell
HTML & CSS for Beginners Part 20: How to center a div
Kevin Powell
HTML & CSS for Beginners Part 21: How to create a basic website layout - the HTML
Kevin Powell
HTML & CSS for Beginners Part 22: How to create a basic layout - the CSS
Kevin Powell
How to Create a Responsive Website from Scratch - Part 1: The HTML #Responsive #HTML5
Kevin Powell
How to Create a Responsive Website from Scratch - Part 2: The Header and Hero area #Responsive #CSS3
Kevin Powell
How to Create a Responsive Website from Scratch - Part 3: The About Section #Responsive #CSS
Kevin Powell
How to Create a Responsive Website from Scratch - Part 4: Building a Responsive Portfolio Section
Kevin Powell
How to Create a Responsive Website from Scratch - Part 5: Call To Action and Footer #CSS #Responsive
Kevin Powell
Tutorial: Learn how to use CSS Media Queries in less than 5 minutes
Kevin Powell
End of the year upate and what's coming to my channel to start the new year
Kevin Powell
Create a CSS only Mega Dropdown Menu
Kevin Powell
CSS Tutorial: Outline and Outline Offset
Kevin Powell
CSS Blending Modes
Kevin Powell
Parallax effect | 2 different ways to add it with jQuery
Kevin Powell
CSS Units: vh, vw, vmin, vmax #css #responsive #design
Kevin Powell
How to Create a Website - Complete workflow | Part 01: Intro + Setting things up
Kevin Powell
100 Subscribers speed coding bonus video
Kevin Powell
How to Create a Website - Complete workflow | Part 02: The Markup #HTML
Kevin Powell
How to Create a Website - Complete workflow | Part 03: Sass Variables and a Mixin #Sass
Kevin Powell
How to Create a Website - Complete workflow | Part 04: Setting up the hero and header
Kevin Powell
How to Create a Website - Complete workflow | Part 05: Typography & Buttons
Kevin Powell
How to Create a Website - Complete workflow | Part 06.1: Building the navigation with Flexbox
Kevin Powell
How to Create a Website - Complete workflow | Part 06.2: Making the nav work with jQuery
Kevin Powell
Redesigning & Coding My Website #CreateICG
Kevin Powell
How to Create a Website - Complete workflow | Part 07: Starting the flexbox grid
Kevin Powell
How to Create a Website - Complete workflow | Part 08: Promo & Problem shooting!
Kevin Powell
How to Create a Website - Complete workflow | Part 09: The CTA and Footer
Kevin Powell
How to Create a Website - Complete workflow | Part 10: Making it responsive
Kevin Powell
How to Create a Website - Complete workflow | Part 11: Making it responsive con't
Kevin Powell
How to Create a Website - Complete workflow | Part 12: Putting the site online
Kevin Powell
Create a Custom Grid System with CSS Calc() and Sass
Kevin Powell
CSS em and rem explained #CSS #responsive
Kevin Powell
Should you use Bootstrap?
Kevin Powell
How to add Smooth Scrolling to your one page website with jQuery
Kevin Powell
Let's learn Bootstrap 4
Kevin Powell
How I approach designing a website - my thought process
Kevin Powell
Build a website with Bootstrap 4 - Part 1: The setup
Kevin Powell
Build a website with Bootstrap 4 - Introduction
Kevin Powell
Build a website with Bootstrap 4 - Part 2: Customizing Variables
Kevin Powell
More on: Prompt Craft
View skill →Related Reads
Chapters (8)
Introduction
0:30
The basics of nesting
4:45
Don’t over nest
5:30
The & character (ampersand)
8:55
How & works behind the scenes and a potential problem you could run into
13:45
It doesn’t work with BEM
16:45
Searchability isn’t an issue
17:40
My favorite use case
🎓
Tutor Explanation
DeepCamp AI