- Mastering CSS
- Rich Finelli
- 462字
- 2025-02-26 11:48:47
Classes
Look at the index.html file. You can see there are several HTML5 <section> tags throughout the page: one in the initial section, one in the secondary section, and one in the alternate section, making three all together. One of those is shown below:

Inside the second <section>, there are three div tags, each housing an img, h2, p, and an a tag. So there is nothing fancy about this HTML. The last section looks a lot like the first section; it just has h1 and h2 elements and a couple of paragraphs. Here's the dilemma, though: we want h1 at the bottom of the page to be different from the site's main h1 element. The solution is to add a class and a style based on this class. So, down in the alternative section, inside of the h1 element, we're going to add the class attribute. We'll type class="" and enter any name or abbreviation we think is fitting:
<h1 class="">Feeding Frenzy</h1>
I'll tell you right now the hardest job in programming and computer science is naming things. This name should be meaningful enough so that if another person comes across your code and were to pick up from where you left, they won't be completely lost. So, in our case, we'll use alt-headline. Classes are case-sensitive, so I recommend you use lowercase and separate words using a dash, which is the common naming convention in CSS. If you use a space, it will be seen as two classes, and that's really not what we want to do:
<h1 class="alt-headline">Feeding Frenzy</h1>
So we'll save our HTML and hop over to our CSS.
Underneath h1, we will add our class name, preceded by a period as our selector. Type .alt-headline and add a font size of 40px:
h1 { font-size: 70px; line-height:1.4; font-weight: bold; color: #0072ae; } .alt-headline { font-size: 40px; }
Before we save this, we'll make this CSS window smaller so we can see our site adjacent to our code. Scroll down to h1 on your site and you will see in the preview on the left-hand side that it's currently 70px:

When you save the CSS, h1 becomes 40px:

I put this new rule set below the original h1 rule set, and you might think that because it comes second, it overwrites the one above it. That's actually not what's happening here. Even if I were to switch this rule set to be above h1, it would still be 40px. This is because classes carry more weight than an element when used as a selector:
.alt-headline { font-size: 40px; } h1 { font-size: 70px; line-height:1.4; font-weight: bold; color: #0072ae; }
Following is the output of preceding code:

For good measure though, let's keep the alt-headline rule set below the original h1 selector.