Wednesday 1 November 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:



            class='outer'>

class="inner">...


class="middle">
...






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.



data-hide="false" data-console="true" data-babel="false">
class="snippet-code">
div {
border: 1px solid
black;
padding: 10px;
}
.outer > div {

border: 1px solid orange;
}

class="snippet-code-html lang-html prettyprint-override"> class='outer'>
div.outer - This is the parent.
class="middle">
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.


class="middle">
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




class="middle">
...




class="inner">...








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.



href="http://www.quirksmode.org/css/selectors/">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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...