Chapter 15: Applying CSS

Now that you know a CSS technique, that is, the fabulous background-color setter, I shall show you a range of ways of applying CSS. CSS is truly powerful in that, you can apply it to all elements of a certain type, all elements with a certain ID, or all elements with a certain class. Since you choose which elements have which IDs and Classes, this literally means you can style any element in any way you want.

Styling All Elements of a Certain Kind

The last chapter was an example of doing just this. I demonstrated styling all h1s, all h2s, all h3s, all h4s, all h5s and all h6's, and made them all have a red background. I also demonstrated styling the body, and gave it a black background. So, if you wanted to style all of the paragraphs on a certain page?

p
{
 ...style settings here...
}

Styling Elements with a Certain Class

Let's say I have several elements which have given the class attribute set to "sub-section". To make them all take on a certain style, I put a full stop, followed by the class name within my style information:

.sub-section
{
 ...style settings here...
}

Now, all elements on the web-page that have class="sub-section" will take on the styles set.

Styling Elements with a certain ID

Remember that every ID should be unique, and you can give any element an ID.

To style an element with a specific ID, you simply put a hash symbol # followed by the id name. So for example if I gave the first paragraph in my document an ID of "first-paragraph" like so:

<p id="first-paragraph">Arooga!</p>

To style that paragraph, I would put this in my style information

#first-paragraph
{
 ...style settings here...
}

This would make the paragraph above take on whatever style settings that were in place of the text "...style settings here". Generally, if you have multiple elements with the same ID, which you shouldn't have, most browsers will apply the styles you set for that ID to each element with that ID anyway. This is a bad practice and is incorrect use of the ID attribute. The browsers are just very kind to bad coders! If you want to have certain elements take on the same style, then you need to use the Class attribute.

Try setting CSS styles in different ways yourself, take the quiz, and then let's get back to learning the different styles you can set.