Can an HTML element have multiple classes?

Question

Can an HTML element have multiple classes?

Answer

Yes! An HTML element can have multiple classes. To give an element multiple classes we use this syntax: class="class-one class-two class-three ...". For example, in the following code we are applying three styles from three different class selectors on the same element:
HTML:

<!DOCTYPE html>
<html>
<head>
  <title>My Site</title>
</head>
<body>
  <h1 class="greeting hello-world heading">Hello World</h1>
</body>
</html>

CSS:

.greeting {
  font-family: monospace;
}

.hello-world {
  color: blue;
}

.heading {
  font-size: 34px;
}
2 Likes

Why would we want to use multiple classes?

2 Likes

Yes, it definitely can. Sometimes that is very helpful too.

For example, if you have a class that makes text inside of it red (useful for errors, required form inputs, etc.) you will want to be able to use it on elements that sometimes need another tag too.

Example:

<p class="bold red-text">Please fill this out!</p>

You probably want this to stand out. You might have a class bold and a class red-text. You want both of these applied, but you don’t want to create another class for bold paragraphs with red text. You simply put in both classes with a space in between.

Remember always to put a space between the names of the classes!

5 Likes

It’s actually very common. People usually have some classes that they think they will use over and over. (e.g. Red text) and they sometimes want to use to different classes on the same element without having to write a whole other class.

1 Like

Might just be because I haven’t covered it yet, but how have you made only the selected words ‘this out’ bold rather than the whole sentence under the class selector? If that makes sense?

Hello!

I’m not actually sure what happened there-- that’s just a code snippet, not the actual result of what it will look like. Looks like it might some quirk of Codecademy’s code display thing? Not sure.

1 Like

hey @lara30! if I am understanding your question correctly, you are able to do that in HTML (making only certain parts of words bold) using the tag!

Or check this out for more info:

1 Like

Yes this is exactly what I was looking for, thank you!

Awesome, I’m so glad it helped!!

1 Like