开发者

What does this css selector syntax mean?

开发者 https://www.devze.com 2023-03-27 09:30 出处:网络
I have seen the syntax: ul#nav开发者_StackOverflow社区 li a { } And im not really sure what it means, is it the same as saying:

I have seen the syntax:

ul#nav开发者_StackOverflow社区 li a
{
}

And im not really sure what it means, is it the same as saying:

#nav ul li a

?

I guess I dont really understand what it means to have an element type before an id selector with no space...


ul#nav will apply to <ul id="nav">

whereas:

#nav ul will apply to any <ul> within the <tag id="nav">


ul#nav li a will select:

  • <a> elements...
  • That are within a <li> element...
  • That are within a <ul> with id attribute equal to nav.

It won't select descendants of any element that is not a <ul>, even if it's id is nav.

It is a bit redundant, as ids are unique. For all practical purposes, #nav li a will do.


Is it the same as saying: #nav ul li a?

Note that #nav ul li a is not the same, this would select the a within an li if it is a descendant ul of another element with id nav.

<div id="nav">
  <ul>
    <li><a>This would be selected</a></li>
  </ul>
<div>

<ul id="nav">
  <li><a>This would not be selected</a></li>
</ul>

I guess I dont really understand what it means to have an element type before an id selector with no space...

You can combine multiple selectors on one element. Here's a silly example:

a#message.error.active[rel="foobar"]:hover {}

This will select an <a> element with id="message" when it is hovered, only if it has the class error, as well as the class active, and it's rel attribute is foobar.


The basics are explained here: http://www.w3.org/TR/CSS2/selector.html


That selects an anchor inside a list item inside an un-ordered list that has the ID 'nav'

So

<ul id='nav'>
    <li>
        <a href='test.com'>Test</a>
    </li>
<ul>
<ul>
    <li>
        <a href='test.com'>Test</a>
    </li>
<ul>

It would match the first Anchor, not the second.

It's not the same as the second, if it works at all it'd only match where the UL had a parent with an ID of 'nav'.


It's worth noting that while the tag#id_name syntax is redundant because id's are unique, that syntax is useful when dealing with classes.

ul.nav li { } can be used to differentiate between multiple tags of the same class.

Like this:

  <ul class="nav">
    <li>Stuff</li>
  </ul>
  <ol class="nav">
    <li>First Item</li>
  </ol>

ul.nav li { } will affect "Stuff" while ol.nav li { } will affect "First Item."

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号