Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply style only on child elements in the first level

Tags:

css

<ul>
  <li> <span> apply </span> </li>
  <li> <span> apply </span> </li>
  <li> 
    <ul>
      <li> <span> ignore </span> </li>
      <li> <span> ignore </span> </li>
    </ul>
  </li>
</ul>

How can I apply a CSS rule only to span elements from the first level, and make span elements from the nested list ignore the rule?

Can this be done without specifically resetting the properties on the 2nd level spans?

Tried ul > li span but it doesn't seem to work, I get the styles applied to 2nd level too

like image 882
Alex Avatar asked Apr 23 '12 14:04

Alex


People also ask

How do I get CSS only for my first child?

The :first-child selector is used to select the specified selector, only if it is the first child of its parent.

How do I apply CSS to child element based on parent?

It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinators (>), which are placed between two CSS selectors.


2 Answers

Put your list in a wrapping div with an ID, for example <div id="ul-wrapper">, and try:

#ul-wrapper > ul > li > span {
    /* my specific CSS */
}
like image 146
sp00m Avatar answered Sep 22 '22 03:09

sp00m


As long as the parent of the outer ul isn't another li, you can use that as the starting point for your selector (example assuming it's a div):

div > ul > li span {
    /* Whatever */
}
like image 45
James Allardice Avatar answered Sep 22 '22 03:09

James Allardice