By the end of this lesson you will be able to apply classes to elements within a web page and understand how they are used in CSS selectors.
A class is an attribute that can be added to any HTML element to give it a name that can be referenced by CSS or JavaScript. Unlike an id, a class can be used on multiple elements.
class attribute inside the start tag of an element.Example:
<div class="highlight">Important text</div>
<p class="note warning">Check this warning</p>
When an element needs several styles, list each class name separated by a space.
<span class="bold italic red">Styled text</span>
In a style sheet the period (.) precedes the class name.
.highlight { background-color: #ff0; }
.note { font-size: 0.9em; }
.warning { color: #c00; }
The final appearance of an element is the result of all classes applied to it, combined with the cascade rules.
When several rules match the same element, the rule with the higher specificity wins. The basic specificity values can be expressed as:
$$ \text{Specificity} = (a, b, c) $$where:
| Rule | Explanation |
|---|---|
| Use lowercase letters | Consistent and easy to read (e.g., menu-item) |
| Separate words with hyphens | Improves readability; avoid underscores or camelCase |
| Be descriptive | Names should reflect purpose, not appearance (e.g., error-message not red-text) |
| Avoid reserved words | Do not use names like class or id |
example.html.title and the paragraph the classes intro and highlight.styles.css, define the classes.<link rel="stylesheet" href="styles.css">.HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Class Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1 class="title">Welcome to My Site</h1>
<p class="intro highlight">This paragraph uses two classes.</p>
</body>
</html>
CSS code (styles.css):
.title {
font-family: Arial, sans-serif;
color: #003366;
}
.intro {
font-size: 1.1em;
}
.highlight {
background-color: #ffff99;
}
menu-item vs menu_item).id with conflicting styles without understanding specificity.nav-link to each link..nav-link display as inline‑block, add padding, and change colour on hover.active to the link that represents the current page and style it with a different background colour.Classes are a flexible way to group elements for styling and scripting. By assigning one or more class names to an element and defining matching selectors in CSS, you can control the presentation of many elements efficiently. Remember to use clear, consistent naming and to separate multiple classes with spaces.