Class selectors
Lesson 4 of 15 in Coddy's CSS Selectors course.
A class selector is a type of CSS selector that selects elements that have a specific class attribute. The class attribute is a custom attribute that you can add to HTML elements to group them together.
To select elements with a specific class, you use a period (.) followed by the class name. For example, the selector .my-class selects all elements that have the class my-class.
Here is an example of how to use a class selector to style a web page:
.my-class {
color: red;
font-size: 2em;
}To add a class to an element write:
<div class="my-class"></div>This CSS rule will style all elements that have the class my-class to be red and have a font size of 2em.
Challenge
Easy- Create a web page with three
h1elements. - Add a class to the first
h1element. - Add another class to the second
h1element. - Use a CSS class selector to style the first
h1element to be red and have a font size of 64px. - Use another CSS class selector to style another
h1element to be blue and have a font size of 32px.
Try it yourself
<html>
<head>
<title>Class Selector Exercise</title>
<style>
/* CSS Code goes here */
</style>
</head>
<body>
</body>
</html>
All lessons in CSS Selectors
3Combinator Selectors
Child selectorDescendant selectorAdjacent sibling selectorGeneral sibling selector