css – 选择器之间的差别div p(plus)和div_p(波形)

前端之家收集整理的这篇文章主要介绍了css – 选择器之间的差别div p(plus)和div_p(波形)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
方式 w3schools短语它,他们听起来一样。

07001

div + p
Selects all <p> elements that are placed immediately after <div> elements

div ~ p
Selects every <p> element that are preceded by a <div> element

如果< p>元素紧跟在< div>元素,并不意味着< p>元素前面有一个< div>元件?

无论如何,我正在寻找一个选择器,我可以选择一个元素,紧挨着一个给定的元素之前。

解决方法

相邻兄弟选择器X Y

Adjacent sibling selectors have the following Syntax: E1 + E2,where
E2 is the subject of the selector. The selector matches if E1 and E2
share the same parent in the document tree and E1 immediately precedes
E2,ignoring non-element nodes (such as text nodes and comments).

ul + p {
   color: red;
}

In this example it will select only the
element that is immediately preceded by the former element. In this
case,only the first paragraph after each ul will have red text.

ul + p {
    color: red;
}
<div id="container">
    <ul>
        <li>List Item</li>
        <li>List Item</li>
        <li>List Item</li>
        <li>List Item</li>
    </ul>
    <p>This will be red</p>
    <p>This will be black</p>
    <p>This will be black</p>
</div>

一般兄弟选择器X〜Y

The ~ combinator separates two selectors and matches the second
element only if it is preceded by the first,and both share a common
parent.

ul ~ p {
   color: red;
}

This sibling combinator is similar to X + Y,however,it’s less
strict. While an adjacent selector (ul + p) will only select the first
element that is immediately preceded by the former selector,this one
is more generalized. It will select,referring to our example above,
any p elements,as long as they follow a ul.

ul ~ p {
  color: red;
}
<div id="container">
  <ul>
    <li>List Item
      <ul>
        <li>Child</li>
      </ul>
    </li>
    <li>List Item</li>
    <li>List Item</li>
    <li>List Item</li>
  </ul>
  <p>This will be red.</p>
  <p>This will be red.</p>
  <p>This will be red.</p>
  <p>This will be red.</p>
</div>

资源

code.tutsplus

General sibling selectors MDN

Adjacent sibling selectors w3

原文链接:https://www.f2er.com/css/221615.html

猜你在找的CSS相关文章