In the book, we learned that we can pick out parts of the page which have a particular meaning by using the class attribute. For instance, the Nanonauts wanted to be able to style their Top Tips so they stand out on the page, without having to style each one individually. To do that, they created a class called top-tip which they can apply to whichever <p> paragraph elements they like.
border:4px solid #00AFEB;
content:"TOP TIP: ";
They then added that style to the <p> paragraph element, in the HTML. So:
<p class="top-tip">Everything inside this element now has the top-tip class.</p>
Let's look at what this does.
In the first rule above, we have added:
- 4 pixel solid blue border around the paragraph
- Curved edges on that border
- Some padding between the text and the border
- A lighter blue background color inside the border
The second rule contains something we haven't seen yet – '::before'. This is called a pseudo-element, which you can recognize because of the double colon.
This pseudo-element tells the browser to insert the rule's content BEFORE the content of the <p> element. The content is the text "TOP TIP: " in black, bolded text. This means we don't need to add that text to Top Tips in the HTML – it gets added automatically by the top-tips class.
There are other pseudo-elements you can use in this way:
- ::first-line applies the rule's content only to the first line of text in a <p> element
- ::first-letter applies it only to the first letter in a <p> element
- ::after inserts the rule's content after the content of the <p> element
- ::selection applies the rule's content to text that is selected by the user.
What if we wanted to apply more than one class to an element? Well, that's easy – you can apply as many as you like. Let's say you have defined two classes:
- "makeBig" has a css rule to increase the size of the font.
- "allCaps" has a rule to capitalize the text.
You can add both of these classes to a <p> element just by putting them both in the class attribute, with a space between them:
<p class="makeBig allCaps">This text will now be bigger and appear in capital letters.</p>