skip to Main Content

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?

2

Answers


  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 */
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search