CSS选择器-何时使用“>","+"和"+"之间的区别或"" [英] CSS Selectors - difference between and when to use ">", "+" or " "
问题描述
使用CSS时,我可以通过以下方式查询元素:
When using CSS, I can query elements in the following ways:
div > .class
div .class
div + .class
但是,我不太清楚这两个DOM
查询之间的确切区别.它们是否都指向子元素?我知道>"和"(空格).
However I can't quite tell the exact difference between each of these DOM
queries. Do they all point to child elements? I know that ">" and " " (space) do.
但是我会在什么情况下使用它们?
But under what circumstances would I use each?
推荐答案
在CSS中,它们称为组合器,表示三种不同的含义:
In CSS these are called Combinators and means three different things:
-
div > .class
:称为 子选择器 ,并将选择所有div
的直接子元素并具有.class
类的元素.
div > .class
: is called Child selector and will select all elements that are direct children of adiv
and have the class.class
.
div .class
:称为 后代选择器 ,并会选择div中所有具有类.class
的元素.
div + .class
:称为 相邻兄弟姐妹选择器 ,并将匹配紧随div
并具有类.class
的任何元素.
div + .class
: is called Adjacent sibling selector and will match any element that immediately follows a div
and have the class .class
.
示例:
在以下示例中:
<div>
<p class="test">
<a href="#" class="test">
Testing link</a>
<img class="test"/>
</p>
<span class="test">A span</span>
</div>
<h4 class="test">A title</h4>
-
div > .test
将仅匹配<p>
和<span>
元素. -
div .test
将匹配<p>
,<a>
,<img>
和<span>
元素. -
div + .test
将仅匹配<h4>
元素,因为它会紧随<div>
之后. div > .test
will match only<p>
and<span>
elements.div .test
will match<p>
,<a>
,<img>
and<span>
elements.div + .test
will match only<h4>
element because it follows the<div>
immediately.
演示:
div .test {
background: yellow;
}
div>.test {
background: red;
}
div+.test {
background: green;
}
<div>
<p class="test">
Pragraph
<a href="#" class="test">
link</a>
<img class="test" width="50px" height="50px" />
</p>
<span class="test">Span</span>
</div>
<h4 class="test">Title</h4>
这篇关于CSS选择器-何时使用“>","+"和"+"之间的区别或""的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!