Friday, 3 February 2017

CSS '>' selector; what is it?











I've seen the "greater than" (>) used in CSS code a few times, but I can't work out what it does. What does it do?


Answer



> selects immediate children



For example, if you have nested divs like such:





...




...





and you declare a css rule in your stylesheet like such:



.outer > div {

...
}


your rules will apply only to those divs that have a class of "middle" since those divs are direct descendants (immediate children) of elements with class "outer" (unless, of course, you declare other, more specific rules overriding these rules). See fiddle.





div {
border: 1px solid black;

padding: 10px;
}
.outer > div {
border: 1px solid orange;
}


div.outer - This is the parent.

div.middle - This is an immediate child of "outer". This will receive the orange border.
div.inner - This is an immediate child of "middle". This will not receive the orange border.




div.middle - This is an immediate child of "outer". This will receive the orange border.
div.inner - This is an immediate child of "middle". This will not receive the orange border.




Without Words






...



...








Side note



If you, instead, had a space between selectors instead of >, your rules would apply to both of the nested divs. The space is much more commonly used and defines a "descendant selector", which means it looks for any matching element down the tree rather than just immediate children as the > does.



NOTE: The > selector is not supported by IE6. It does work in all other current browsers though, including IE7 and IE8.



If you're looking into less-well-used CSS selectors, you may also want to look at +, ~, and [attr] selectors, all of which can be very useful.



This page has a full list of all available selectors, along with details of their support in various browsers (its mainly IE that has problems), and good examples of their usage.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...