当前位置: 动力学知识库 > 问答 > 编程问答 >

css - Is `div > a` the same thing as `div a`?

问题描述:

In CSS, are the selectors div > a and div a the same?

<div>

<a>Hi</a>

</div>

网友答案:

It isn't. "div > a" is a child selector; it means "an a element that's an immediate child of a div". "div a" is a descendant selector; it means "an a element that's a descendant of a div" (a child, or the child of a child, or the child of a child of a child, ...). All child elements are, of course, descendants; but not all descendants are children.

So for instance:

<div>
  <a href='http://www.google.com'>Google</a>
</div>

matches both div > a and div a (the a is a child element of a div, and of course all child elements are also descendant elements).

But:

<div>
  <span>
    <a href='http://www.google.com'>Google</a>
  </span>
</div>

...doesn't match div > a but does match div a, because the a is a descendant but not an immediate child (there's a span in-between).

Live example

网友答案:

They're not the same.

网友答案:

It's not.

<div><h1><a>some text</a></h1></div>

In the HTML above, div > a will not select the <a> because it's not a direct child of <div>.

网友答案:

No, they are not the same. The first selects only a elements that are children of div elements, while the second selects all a elements that are descendants of div elements, e.g. <div><p><a>...</a></p></div>.

分享给朋友:
您可能感兴趣的文章:
随机阅读: