Richard Banks
Richard Banks

Reputation: 2983

styling child html elements

I need to style some child elements in the dom but only if they are not a child of a specific element. as an example i need to bold the text in the span in this

<span class="a">
 <span class="b">
  <span class="c">
    bold this test
  </span>
 </span>
</span>

but not in this

<span class="a">
 <a class="SomeOtherclass">
  <span class="b">
   <span class="c">
    not bold
   </span>
  </span>
 </a>
</span>

I dont have control of the output so i cannot change the class names or structure

Upvotes: 2

Views: 92

Answers (5)

Rohit Azad Malik
Rohit Azad Malik

Reputation: 32202

Daniel is Right

and if you need second option than

you can do this

.c{
font-weight:bold;
}

.SomeOtherclass .c{
font-weight:normal;
}

Upvotes: 0

MarmiK
MarmiK

Reputation: 5785

the best way for this is

span.a>a.SomeOtherclass>span.b>span.c{
  font-weight: bold
}

this will be applied to the particular class of particular parent only. Not in the other case.

if you want to reverse it, then it will be like this

span.a>span.b>span.c{
  font-weight: bold
}

it will not be applied in case of you add anything(any tag) in between this hierarchy of DOM.

This will do .. :)

Upvotes: 0

SaurabhLP
SaurabhLP

Reputation: 3655

You can use Child-of selector for it...

For example,

.a { /*Your Style*/ }
.a > .b { /*Your Style*/ }
.a > .b > .c { /*Your Style*/ }

Upvotes: 0

Fenton
Fenton

Reputation: 251252

You could have an overriding rule for the special case, so for example:

.c {
    font-weight: bold;
}

.SomeOtherClass .c {
    font-weight: normal;
}

I have assumed that in the normal case, you don't always have the a, b, c nesting - which is why you are asking to apply this rule except in a particular case.

Upvotes: 0

Daniel Imms
Daniel Imms

Reputation: 50269

You want to use the direct descendant selector >. The selector a > b will select b only if it is a direct descendant (ie. child) of a.

jsFiddle

.a > .b > .c {
    font-weight:bold;
}

Upvotes: 7

Related Questions