FREELessons: 10Length: 34 minutes

Next lesson playing in 5 seconds

  • Overview
  • Transcript

2.4 Heading Counters

Wouldn’t it be nice if there were a way to automatically apply numbers to all of the h3 elements in your articles? In this lesson, you’ll learn how to do just that using CSS counters.

Relevant Links

2.4 Heading Counters

Hello, and welcome back. In this lesson, I wanna talk about how to create counters for your headings within an article. Let's say you have an article with a number of different subheadings and you want those headings to have a number in front of them. But you don't wanna hard code it, because you never know if you're gonna go back and edit it and maybe add a couple more headings in there somewhere. It'd be nice if our browser could just calculate those numbers for us, so we didn't have to keep changing them every time we changed our content. Well, we can do that using counters. And we're gonna talk very briefly in this lesson about how to do that. So you can find the URL for our starting pen here in your course notes for this lesson. Once you open that up, go ahead and click on Fork to create a new copy and I just want to start by changing the font family just to a sans serif for now and then, we'll talk about numbering our headings. So really all we need is if you look at our HTML, first of all, we have a series of H3 elements followed by paragraphs. And these H3 elements are the ones we want to add a counter to. So that our headings will be numbered. So let's jump back into our CSS and take a look at how to do that. Well, the first thing we're gonna do is we're gonna point to the h3 element and we're going to create a counter. And the way we do that is we use the counter increment property and then we can set it equal to a name that we're gonna use ourself. Let's call this h3counter. So we're gonna use this h3counter name inside our h3s, and we're gonna place the number represented by that counter before each of those headings. So we're gonna do that using the before pseudo-class, so h3::before. And then inside that pseudo class we're gonna set the content equal to that counter plus a period. So the way this works is first of all we type in the word counter and then inside parenthesis we're gonna type in the name of the counter that we've created which we call the h3counter. Now, as you can see, that puts a number at the beginning of each of our headings and that's a good start. We just need to add a period and space now. So after our closing parentheses here. I'm just gonna type space and then inside quotation marks here, I'm just gonna type period and a space. And as you can see that gives us the desired effect. So then at the end of that line, we'll just put a semi colon and we're done. So that's how you can create your own automatic counters in CSS in order to add numbers to your headings. Thank you for watching and I'll see you in the next lesson.

Back to the top