-3

I want to style html elements in CSS using class, not id. and I need to assign 2 classes to 1 element. I want one mother class e.g.'animal' and smaller classes e.g. 'mammal' & 'reptile'.

I could just style every element in the smaller classes individually with id's but I'm working on a big project and that would take forever. is there a way to assign two classes to 1 element?

Bro coda
  • 19
  • 6

2 Answers2

1

Yes, you can easily give multiple classes to a single element, just separate them by a space. For example:

<div class="animal mammal reptile">...</div>

Now the above div has 3 classes, animal, mammal and reptile. And now you can target each just like you'd target a single class.

.animal {
  /* styles for animal */
}

.mammal {
  /* styles for mammal */
}

.reptile {
  /* styles for reptile */
}
0

You can add a list of classes to an element, commonly delimited with a space.

But that is not all. A class="..." definition in a HTML tag is also an attribute, so you can use the attribute selector to query that definition for specific values. For example:

/* CSS */
[class="myClass"] { ... }
[class^="my"]     { ... } /* all classes starting with ... */
[class*="Cl"]     { ... } /* all classes containing    ... */
[class$="ass"]    { ... } /* all classes ending with   ... */

[class*="my"][class*="ss"] { ... } /* all classes containing ... and ... */

And so on, limitless posibilities. Check out more attribute selectors on this page CSS Selector Reference.

Rene van der Lende
  • 4,992
  • 2
  • 14
  • 25