TARKUS
TARKUS

Reputation: 2200

CSS: How do I assign one class to multiple elements?

I want to assign one class, like "centered" to some, all, or each of my text elements, like <h1 class="centered">, <h2 class="centered">, <h3 class="centered">, <p class="centered">.

I need to target only specific elements because I may want some different rules for block elements like <div class="centered">.

If you think this question is easy to get an answer for, try Googling it. No matter how I phrase the question, Google thinks I'm asking "how to assign multiple classes to one element". I know how to give an element multiple classes, so, no, that's not what I want.

What I've tried:

h1, h2, h3, p .centered{
    text-align:center;
}

That can't be right. That's just saying the centered class shares the same css rules with h1, h2, and h3.

Right now I'm reduced to this method, which seems inelegant, and probably amateur:

h1.centered{
    text-align:center;
}
h2.centered{
    text-align:center;
}
h3.centered{
    text-align:center;
}

...etc.

Upvotes: 1

Views: 1069

Answers (2)

Tony Scialo
Tony Scialo

Reputation: 5957

Another small piece of advice is you can combine all of your "centered" css rules into one line if you want. So instead of

h1.centered{
    text-align:center;
}
h2.centered{
    text-align:center;
}
h3.centered{
    text-align:center;
}

Do something like this:

h1.centered, h2.centered, h3.centered{
    text-align: center;
}

Upvotes: 6

Nenad Vracar
Nenad Vracar

Reputation: 122047

You just define your class in css and use it on elements you want in html

.centered {
  text-align:center;
}
<h1 class="centered">Lorem ipsum.</h1>
<h2 class="centered">Lorem ipsum.</h2>
<h3 class="centered">Lorem ipsum.</h3>
<p  class="centered">Lorem ipsum.</p>

Upvotes: 6

Related Questions