CSS Class Selector
The CSS class selector is used to apply styles to elements with a specific class
attribute. Unlike the ID selector, a class can be reused for multiple elements.
The syntax for the class selector is:
</>
Copy
.class {
property: value;
}
Where:
Parameter | Description |
---|---|
.class | The class name of an HTML element, preceded by a dot (. ). |
property | A CSS property (e.g., color , margin , etc.). |
value | The value assigned to the CSS property. |
Examples
Styling Multiple Elements using Class Selector
In this example, we style all elements with the class highlight
to have a background color of yellow and a font weight of bold.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<p class="highlight">This is highlighted text.</p>
<span class="highlight">This span is also highlighted.</span>
</body>
</html>
Styling Specific Elements with a Class
Here, we style only <div>
elements with the class box
, setting their border to 1px solid black and their padding to 10px.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div.box {
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div class="box">This is a styled box.</div>
<div>This div is not styled.</div>
</body>
</html>
Combining Classes using Class Selector
In this example, we use multiple classes on an element. The .text
class sets the text color to blue, and the .large
class increases the font size to 20px.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.text {
color: blue;
}
.large {
font-size: 20px;
}
</style>
</head>
<body>
<p class="text large">This is large and blue text.</p>
</body>
</html>