Categories
css css-selectors

CSS rule to apply only if element has BOTH classes [duplicate]

327

Let’s say we have this markup:

<div class="abc"> ... </div>
<div class="xyz"> ... </div>
<div class="abc xyz" style="width: 100px"> ... </div>

Is there a way to select only the <div> which has BOTH abc and xyz classes (the last one) AND override its inline width to make the effective width be 200px?

Something like this:

[selector] {
  width: 200px !important;
}

0

    517

    div.abc.xyz {
        /* rules go here */
    }
    

    … or simply:

    .abc.xyz {
        /* rules go here */
    }
    

    7

    • 5

      Also: .abc.xyz is more specific than .abc or .xyz or div so !important is not necessary.

      – Jan

      Apr 26, 2011 at 21:29


    • 3

      So, this will not select <div class="abc"> because it lacks xyz?

      Apr 26, 2011 at 21:30

    • 5

      Exactly so. You can see stackoverflow.com/questions/2554839/… for more info.

      – esqew

      Apr 26, 2011 at 21:32

    • 1

      @Jan. !important would be necessary if an inline style is in place. The inline style from OP’s question will override the CSS class.

      Apr 26, 2011 at 21:35

    • 4

      Note this differs from div .abc .xyz{} which applies to an object with class xyz with its parent having the abc class and the abc class having a div as a parent.

      – Jeff

      Sep 20, 2013 at 18:58


    13

    Below applies to all tags with the following two classes

    .abc.xyz {  
      width: 200px !important;
    }
    

    applies to div tags with the following two classes

    div.abc.xyz {  
      width: 200px !important;
    }
    

    If you wanted to modify this using jQuery

    $(document).ready(function() {
      $("div.abc.xyz").width("200px");
    });
    

    0

      2

      If you need a progmatic solution this should work in jQuery:

      $(".abc.xyz").css("width", 200);
      

      2

      • Thank you, seems there was no problem other than my poor grasp over css!

        Apr 26, 2011 at 21:40

      • 1

        Jquery internally uses document.queryselector and document.queryselectorall in current releases. So, use those instead of jquery if that is all you would be using jquery for.

        – user7892745

        Apr 24, 2017 at 23:42