sdvnksv
sdvnksv

Reputation: 9668

What is the difference between separating CSS items with "space" or ">"

Say, we have this code:

<div>
  <ul>
    <li></li>
  </ul>
</div>

What is the difference between <style>div ul li { ... }</style> and <style>div > ul > li { ... }</style>?

Upvotes: 1

Views: 70

Answers (1)

Mark Simpson
Mark Simpson

Reputation: 2374

The space is a descendant selector. It will apply styles to all matching descendants (children, grandchildren, great-grandchildren...)

The > is a child selector. It will only apply to children of the parent.

Let's use this HTML as an example:

<section class=foo>
    <div class=blue>
        <span class=blue></span>
    </div>
</section>

Let's style it with the descendant selector:

.foo .blue {
    color: blue;
}

With the above CSS, both the div and the span will be blue. In fact, any element inside .foo will turn blue if you give it the class "blue".

Now look at this CSS:

.foo > .blue {
    color: blue;
}

With this CSS, only the div will be blue. The span will not be blue despite having the class "blue", as it is not a child of .foo

Upvotes: 6

Related Questions