I have the following HTML elements:
<div class="class1 class2 class3">
<div class="innerClass">
</div>
</div>
I want to apply style to innerClass
which is in classes : class1
, class2
, class3
no more no less. I mean if there is innerClass
in element with classes class1
, class2
the style should't be applied and if I have innerClass
in element with classes class1
, class2
, class3
, class4
it shouldn't be applied either.
You can use any CSS selector while nesting with spaces, you can use id selectors with #id-name, tag selectors like h1, pseudo-classes, etc.
To be nest-prefixed , a nesting selector must be the first simple selector in the first compound selector of the selector. If the selector is a list of selectors, every complex selector in the list must be nest-prefixed for the selector as a whole to be nest-prefixed.
Multiple classes can be applied to a single element in HTML and they can be styled using CSS.
You can do this with the CSS Attribute selector
The [attribute] selector is used to select elements with a specified attribute.
div[class="class1 class2 class3"] .inner {padding:1em; background:red;}
<div class="class1 class2 class3">
<div class="inner"></div>
</div>
<div class="class1 class2 class3 class4">
<div class="inner"></div>
</div>
<div class="class3 class4">
<div class="inner"></div>
</div>
Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors (added by: Chris Bier)
Edit: As pointed about in the comments by Sidney Liebrand, this approach assumes that the order of the classes is exact and therefore will not work when the order is the following: class="class2 class3 class1"
. One way to solve this is to just add each order combination possible in the rule, like so:
div[class="class1 class2 class3"] .inner,
div[class="class1 class3 class2"] .inner,
div[class="class2 class1 class3"] .inner,
div[class="class2 class3 class1"] .inner,
div[class="class3 class1 class2"] .inner,
div[class="class3 class2 class1"] .inner {
padding:1em; background:red;
}
But as you can see, this is not efficient at all so you'll have to make sure the order is correct or resort to a javascript solution.
If order of classes is quite randomized, you could filter it using:
$('.class1.class2.class3').filter(function(){
return this.classList.length === 3;
}).find('.innerClass').css({prop: value});
You could find polyfill for older browser regarding classList
support or just split className
.
You'd combine the classes like this:
.class1.class2.class3 .innerClass {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With