347

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;
}
Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127

3 Answers3

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

... or simply:

.abc.xyz {
    /* rules go here */
}
esqew
  • 42,425
  • 27
  • 92
  • 132
  • 6
    Also: `.abc.xyz` is more specific than `.abc` or `.xyz` or `div` so `!important` is not necessary. – Jan Apr 26 '11 at 21:29
  • 3
    So, this will not select `
    ` because it lacks `xyz`?
    – Majid Fouladpour Apr 26 '11 at 21:30
  • 5
    Exactly so. You can see http://stackoverflow.com/questions/2554839/select-css-based-on-multiple-classes for more info. – esqew Apr 26 '11 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. – John Hartsock Apr 26 '11 at 21:35
  • @John you are Correct, I misunderstood the question. Still an important part of CSS though that is not understood well enough by most people. – Jan Apr 26 '11 at 21:40
  • @esqew: Don't know what to say - amine's exactly the same question. Looked at suggested list of similar questions while entering mine. That should not have come up. – Majid Fouladpour Apr 26 '11 at 21:45
  • 5
    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 '13 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");
});
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
2

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

$(".abc.xyz").css("width", 200);
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
scrappedcola
  • 10,423
  • 1
  • 32
  • 43
  • Thank you, seems there was no problem other than my poor grasp over css! – Majid Fouladpour Apr 26 '11 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. –  Apr 24 '17 at 23:42