The CSS class selector targets all HTML elements that have a matching class name attribute attached to them.
Class selector syntax:
.class-name {
property-name: value;
}
Here’s an HTML element with that same class name as an attribute value:
<div class="class-name"></div>
The CSS class selector .class-name
is attached to the <div>
element with the class-name
attribute. That means that whatever styling properties you add to .class-name
in your CSS stylesheet get applied to the div.
The dot (.
) before the name of the class is a specific CSS syntax. When you add the class name to an HTML element as a class attribute you don’t use .
.
Now let’s use what we just learned in a practical example.
Here’s an HTML <button>
element with some default styling that is inherited from the browser’s User Agent Stylesheet:
<button>Button</button>
Default look:
Boring huh?
Let’s override the default button styling by creating a CSS class called .my-button
and give it some styling properties:
.my-button {
font-size: 18px;
padding: 14px 24px;
border-radius: 8px;
border: none;
background-color: #F7575C;
color: white;
}
And add to the button element as a class attribute:
<button class="my-button">Button</button>
Result:
You have just learned the most important things you need to know about using the CSS class selector.
Good to know:
- CSS classes can be reused on any HTML element, unlike ID selectors, which can only be used once.
- You can add multiple different CSS classes to the same element
<div class="first-class second-class third-class"
. This gives you a flexible way to assemble your element designs with small utility classes, such as seen with the Tailwind CSS framework.