I am creating a div that will have a default style but is also going to have various options for different styles depending on the content. My goal is to be able to have these styles take effect only when nested inside of the custom class name. Kind of hard to explain verbally so I'll give some code examples of what I mean:
This will be the html structure for the default view:
<div>
<div class="default"></div>
</div>
This will be the html structure for the custom view:
<div class="custom">
<div class="default"></div>
</div>
So basically I need to be able to write a class that will say "redefine these styles on default only when default is nested inside of custom"
Really just looking for confirmation on the syntax involved here.
My first thought is to write something like:
.custom .default {
declaration: attribute;
}
I'm just a little unsure of whether this will only target default when it's inside of custom or if this will globally redefine default, I can't live test it just yet because ftp transfer hasn't yet been set up for me on this server.
Thanks in advance for any clarity on this!
Yes, that's right. This will target any .default
contained by a .custom
(at any point in its ancestry) (fiddle):
.custom .default {
color: red;
}
See the descendant combinator and others.
And yes, it can override declarations specified by .default
(fiddle):
.default {
color: green;
}
.custom .default {
color: red; /* overrides green */
}
Have a look at selector specificity.
So, canon's answer is enough... But, just for the clarity that you asked.
You can restrict your selector to target only a nested element, with two methods:
MDN ref docs
.parent .child {
/*styles*/
}
>
charachter, and targets the child only if it is directly nested, an immediate child:MDN ref docs
.parent > .child {
/*styles*/
}
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