Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Targeting a class when inside another class

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!

like image 387
tganyan Avatar asked Sep 11 '14 20:09

tganyan


2 Answers

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.

like image 163
canon Avatar answered Oct 20 '22 23:10

canon


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:

  • Descendant Selector: It's written with a white space and targets the child element at any nested level inside the parent:

MDN ref docs

.parent .child {
    /*styles*/
}
  • Child Selector: It's written with a > charachter, and targets the child only if it is directly nested, an immediate child:

MDN ref docs

.parent > .child {
    /*styles*/
}
like image 43
LcSalazar Avatar answered Oct 20 '22 22:10

LcSalazar