Demo
Summary
HTML syntax:
<h1 class="class-name">Main Title</h1>
<h2 class="class-name">Subtitle</h2>
CSS syntax:
.class-name {
/* Insert code here */
}
Details
The class selector allows you to apply styles to multiple elements that contain the class name in their class attribute. This allows you to easily reuse styles and write less CSS.
To create a class selector in CSS, write a period and then the name of the class. If the class name consists of multiple words, you can separate the words using hyphens.
Add curly braces after the class selector and add your properties and values inside the curly braces.
.class-name {
/* Insert code here */
}
To use that class selector inside your HTML code, you can add the class attribute to one or more elements and add the class name inside the quotes. You don’t need to use a period with the class name inside your HTML code. Now the styles in the CSS rule will affect these elements.
<h1 class="class-name">Main Title</h1>
<h2 class="class-name">Subtitle</h2>
Multiple classes
Let’s say you had multiple classes in your CSS file, like this:
.first-class {
}
.second-class {
}
You can apply multiple classes to an HTML element by adding the class names to the class attribute and separating them with a space, like this:
<h1 class="first-class second-class">Main Title</h1>
Please note that if you have multiple classes modifying the same property, only one rule will be applied to the element.
You can also write CSS rules that target elements with a specific combination of classes like this:
.first-class.second-class {
color: red;
}
The selector above would target elements that have both first-class
and second-class
. It would not affect elements with only first-class
or only second-class
.
<!-- This h1 would be affected by the rule above -->
<h1 class="first-class second-class">Main Title</h1>
<!-- This h2 would not be affected by the rule above -->
<h2 class="first-class">Main Title</h2>
Targeting a specific type of element with a class
If you’re using a class on different elements and want to apply some styles to only one type of element, you can use the following selector:
/* Pseudocode */
element.class-name {
}
Just replace the word element with the element type you want to target (like p
, h1
, h2
, etc.), and replace the class name with the class you want to target.
/* Real example */
p.bold-text {
}
h1.bold-text {
}
Exercises
Recreate the HTML and CSS code from the Demo section in your HTML and CSS files.
References
class attribute on MDN
Class selectors on MDN