CSS Selectors

CSS class selectors are responsible for selecting elements with a very particular class attribute.

This is valuable when you want to adjust more than just one element.

For instance, if you want to style multiple paragraphs into blue and others in the colour green, then you need to specify two-paragraph classes.

You would set the class as follows in your HTML document.

<p class=“blue”>Blue text goes here</p>

<p class=“green”>Green text goes here</p>

The class text can be named anything, we’ve just named it as the color so it’s easy to coordinate.

In your CSS file, you would then declare the paragraph tag twice however with the class as well, so it would look like:

p.blue {color: blue}
p.green {color: green}

A full stop precedes class selectors (“.”)

This is a useful selector because you can add multiple values to a <p> tag and it will automatically get filtered to the p.blue and p.green classes.

Through this method, you can describe as many properties, including font and size. Your class also does not need to be tied to an element like paragraph.

Example:

.style1 {
color: blue;
font-weight: bold;
font-size: 12px;
}

And in your HTML document, you would use:

<p class=“style1”>Style 1 text goes here</p>

or

<h2 class=“style1”>Style 1 text goes here</h2>

or any other tag that you want to style as style1

You can use class=”style1″ multiple times and for multiple tags.

The second related concept is id selectors.

 

What are CSS id selectors?

CSS id selectors are used to style a single HTML element, they cannot be used multiple times.

Id selectors are written after a #.

Example:

#style2 {
color: blue;
font-weight: bold;
font-size: 12px;
}

<p id=”style”>Style 2 text goes here</p>

This will change this paragraph to have the styling outlined in style2 above and cannot be used again on the main page.

So to reiterate:

Use class to define styles in your CSS stylesheet and use that class as many times as you want with as many different HTML elements as you want.

Use id to define styles in your CSS stylesheet and use that id for one single HTML element. Id selectors are sometimes defined in the HTML document themselves if there aren’t too many and its a simple 1 page landing page for example.