Lesson 5: CSS Part 2

Let’s take this example from the previous lesson:

<!DOCTYPE html>
<html>
<head>

<style>
	h1 {
		color:red;
	}

</style>
</head>
<body>

	<h1>Hello</h1>

</body>
</html>

In the above code, the h1 selector applies the following styles to all h1 tags in an HTML documents. What if you only wanted the styles to be applied on to only one h1 tag? Or even a few selected h1 tags.

CSS supports many types of selectors that helps you style the specific element you want.

CSS Class and ID Selectors

To differentiate the styles we apply to the same element, we can use class or id selectors in CSS. To use class selectors, we must first add a class attribute to the element we are trying to style. Lets use our previous “Hello” example to showcase how to use CSS class selectors.

<!DOCTYPE html>
<html>
<head>

<style>
	.hello {
		color:red;
	}

</style>
</head>
<body>

	<h1 class="hello">Hello</h1>

</body>
</html>

The above example added a class attribute to the h1 tag. The value of the class attribute can be anything you want. To style the h1 tag, we can select it by using the .hello selector, which selects all HTML elements with a class attribute of “hello”.

Lets add another h1 tag with a different class, and make its text color green.

<!DOCTYPE html>
<html>
<head>

<style>
	.hello {
		color:red;
	}
	
	.hi {
		color:green;
	}

</style>
</head>
<body>

	<h1 class="hello">Hello</h1>
	<h1 class="hi">Hi there</h1>

</body>
</html>

You can see how class selectors are useful in this scenario. When you have tags of the same element that you want to style differently, use class selectors.

There are also id selectors, which are very similar to class selectors. The only difference is that you must include an id attribute to your HTML elements, and to select a tag with any id attribute, you include a # before the id name instead of a ..

Here is an example of rewriting above example using id selectors:

<!DOCTYPE html>
<html>
<head>

<style>
	#hello {
		color:red;
	}
	
	#hi {
		color:green;
	}

</style>
</head>
<body>

	<h1 id="hello">Hello</h1>
	<h1 id="hi">Hi there</h1>

</body>
</html>

I encourage to play around and include more HTML tags with classes and attributes. Get comfortable with these example as we are going to be using them a lot when we build your personal website.