AlexBrand
AlexBrand

Reputation: 12429

Problematic to use the child selector (>) in CSS?

I am not sure if I remember correctly, but I think I read once that using the > selector in css rules was bad practice? Can someone shed some light on this topic?

For example:

<style>
#search-form {
 ... whatever rules...
}
#search-form > input[type=text] {
 ... rules...
}
#search-form > button {
 ... rules ...
}
</style>
<form id="search-form">
    <input type="text" placeholder="Search...">
    <button>Search!</button>
</form>

Upvotes: 0

Views: 439

Answers (3)

Paul Marbach
Paul Marbach

Reputation: 36

It's certainly not bad practice, but should be used with knowledge of the benefits and disadvantages. Using the child selector (E > F) will select only immediate children and, since this prevents complete descendant traversal, will take the browser less time to apply then a descendant selector (E F). However, the element isn't supported in IE6, so if that matters to you, steer clear.

This has a good write up and some nice links: CSS child vs descendent selector

Upvotes: 2

Irfy
Irfy

Reputation: 9587

The child selector matches only the immediate descendant of the left-side selector. It may, or may not be what you want, but applying a certain style for all descendants, regardless of how deep under the left-side selector they are, is more common.

With e.g. #mydiv > span ask yourself: do I really not want to match a span within a p under #mydiv. What about a span in a li within #mydiv? Etc. Maybe you don't -- maybe you do. The important part is to understand what it does.

Upvotes: 1

Guffa
Guffa

Reputation: 700640

The > selector is not supported in IE6, so if you need to support that old browsers you can't use it.

http://caniuse.com/#feat=css-sel2

Other than that, there is no reason not to use it.

Upvotes: 1

Related Questions