CSS选择器-何时使用“>","+"和"+"之间的区别或"" [英] CSS Selectors - difference between and when to use ">", "+" or " "

查看:108
本文介绍了CSS选择器-何时使用“>","+"和"+"之间的区别或""的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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:

  1. div > .class:称为 子选择器 ,并将选择所有div的直接子元素并具有.class类的元素.

  1. div > .class: is called Child selector and will select all elements that are direct children of a div 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选择器-何时使用“&gt;","+"和"+"之间的区别或"&quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆