Reputation: 633
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!
Upvotes: 6
Views: 21175
Reputation: 41665
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.
Upvotes: 15
Reputation: 16821
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:
.parent .child {
/*styles*/
}
>
charachter, and targets the child only if it is directly nested, an immediate child:.parent > .child {
/*styles*/
}
Upvotes: 6
Reputation: 37701
You were right. And if you want to make sure to target only the direct descendants, you can do this:
.custom > .default {
declaration: attribute;
}
That would be helpful in case you had something like:
<div class="custom">
<div class="default">
<div class="default"></div>
</div>
</div>
Upvotes: 1
Reputation: 4079
CSS will look for an element that has a class of default
which is encapsulated within a parent with the class custom
, any child nodes which match this rule will have the styling applied to them, you can create as many different themes for the same element as you wish, so long as you change the class.
So your code:
.custom .default {
declaration: attribute;
}
Is perfectly correct.
Upvotes: 0