1

Here are two examples of css selectors and I can't tell what the difference is and therefore, which one should be used in which cases:

.foo-class a{
    /* this will select all anchor tags inside foo-classes */
}

.foo-class > a{
    /* this will also select all anchor tags inside foo-classes, no? */
}

EDIT: I just found the answer. ">" only selects direct children. I'll leave the question up here in case others find it useful.

user1457366
  • 659
  • 3
  • 13
  • 19

2 Answers2

10

> means select only a direct child of foo-class. If you use the first selector, it will select a child at any level under foo-class. In the code below, using > will mean that the first anchor is not selected, because it's not a direct descendant of foo-class however the second one would be.

<div class="foo-class">
    <p>
        <a href="#">Unaffected Link</a>
    </p>
    <a href="#">Affected Link</a>
</div>

There's no "advantage", it's just a different way to control what you select.

rfoo
  • 1,160
  • 1
  • 12
  • 27
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
  • I've also read there are some performance advantages. Meaning, if you *can* use `>` then you should. – Mike Christensen Sep 12 '13 at 22:10
  • @MikeChristensen None of serious consideration that I am aware of. The relatively refined selectors that bound it (`.foo-class`, `a`) should keep it well-behaved. – user2246674 Sep 12 '13 at 22:11
  • 1
    @MikeChristensen their functionality is completely different, so performance is less of a concern here. You should only use `>` when you want that specific functionality. – A.O. Sep 12 '13 at 22:13
  • I've seen this stated in various blogs, and also [this](http://stackoverflow.com/questions/3581000/css-child-vs-descendent-selector) StackOverflow question. – Mike Christensen Sep 12 '13 at 22:25
  • Imagine a huge dom. If the browsers knows to look no further than the direct child, even though the element had thousands of children. Of course it will be faster. But i highly doubt that you would feel the difference. There are far more important things to consider for performance. But personally i think it's good practice. – jah Sep 12 '13 at 22:59
  • CSS gets evaluated right to left, so the amount of children `foo-class` has doesn't matter, rather, the path from the `a` to the root, because the `a` is found first. – Evan Trimboli Sep 12 '13 at 23:11
1

Second one is the direct a child of the .foo-class. The first one is every a inside .foo-class

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Ricardo Mogg
  • 589
  • 6
  • 18