开发者

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

开发者 https://www.devze.com 2023-02-04 17:52 出处:网络
In CSS, are the selectors div > 开发者_JAVA技巧a and div a the same? <div> <a>Hi</a>

In CSS, are the selectors div > 开发者_JAVA技巧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


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>.


They're not the same.


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>.

0

精彩评论

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