Is symbol> necessary when selecting a child element in CSS?

div > p {
    background-color: yellow;
} 

      

does not seem to evaluate otherwise than

div p {
    background-color: yellow;
} 

      

But will there be an effect that I am not aware of? It looks like using> is a more appropriate style, at least.

+3


source to share


5 answers


There is a difference; >

"immediately follows". So yours div > p

will apply to p

here:

<div>
    <p>Text here</p>
</div>

      

but not here:



<div>
    <table>
        <tr>
            <td>
                <p>Text here</p>
            </td>
        </tr>
    </table>
</div>

      

A more detailed description can be found in the CSS specification for child selectors .

+7


source


Take a look at this example, it might help you ...

div#container > ul {

      

border: 1px solid black; }

.......



<div id="container">   <ul>
  <li> List Item
    <ul>
       <li> Child </li>
    </ul>
  </li>
  <li> List Item </li>
  <li> List Item </li>
  <li> List Item </li>   </ul> </div>

      

The #container> ul selector will only target uls that are direct children of the container id div. It will not target, for example, a ul that is a descendant of the first li.

For this reason, there are performance benefits when using a child combinator. In fact, it is recommended, especially when dealing with JavaScript oriented CSS selector mechanisms. ....... Read this: http://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048 it will help you.

+1


source


div > p

selects direct child p

(only sons)
div p

selects all of its children p

, now it matters how deep it is in the hierarchy (including grandchildren and grandchildren).

+1


source


div>p

      

indicates P which is the DIRECT child of the div

div p

      

specifies p being a child of a div, not

Check out the Fiddle for example.

+1


source


Selector> is used to select the children of a specific element.

+1


source







All Articles