Working with the class element
Web Design with HTML & CSS
🕑 This lesson will take about 15 minutes
The class attribute in HTML is used to assign a “class” name to an HTML element. Class names are used to select elements in a web page that you want to style with CSS code and can also be used to access elements with JavaScript code. A class can be used on one or more HTML elements in a web page/site, and also an element can have one or more class names (so you can combine different styles).
Selectors are used to select elements in a web page that you want to style. There are many types of CSS selectors including:
Element selector – element selectors select all of the elements in a web page with the specified element name (eg. p, h1, h2).
Class selector – class selectors apply a style to all of the elements that use that class. Eg. a style of green text with a yellow background could be applied to multiple paragraphs that use that class name.
ID selector – ID selectors are unique for each element and are used when you want to apply a style to just one element on a web page.
and many more.
If you have completed the previous lessons, then you have already used element selectors in your CSS code (eg. to style a paragraph using the p element selector, or a div using the div element selector). In this lesson, we will focus on using the class selector. A class selector can be used when you want to apply a style to all of the elements that use that class name.
When we use classes, we specify the class name in the element tag. In the example below, a paragraph has been assigned a class name “myBlueParagraph”:
<p class = "myBlueParagraph">This text is blue</p>
Then, in the CSS code you need to select the class you want to apply a style to by placing a period/full stop before the class name. A period indicates you are referring to a class name (instead of an element name or an ID).
.myBlueParagraph{ color:blue; }
Watch the video below to see how you can use classes in your web pages. Then scroll down to view the sample code.
Here is the sample HTML and CSS code:
Next lesson: Working with IDs in HTML & CSS