如何选择x元素之后的所有n个元素?

时间:2019-02-04 12:51:13

标签: css

我正在尝试对在我元素之后的所有span进行样式设置,但是我无法实现某些奇怪的事情。我无法按顺序对span元素进行样式设置。

这是我的代码

.header p span:nth-child(1) {
  color: red;
}

.header p span:nth-child(2) {
  color: blue;
}

.header p span:nth-child(3) {
  color: orange;
}
<div class="header">

  <p>
    <i class="fas fa-phone"></i>
    <span>444</span>
    <span>01</span>
    <span>34</span>
  </p>
</div>

3 个答案:

答案 0 :(得分:3)

:nth-​​child也将计算i元素,因此您必须使用索引2、3和4才能使其正常工作。或者,如果您只想包含跨度元素,则可以使用:nth-of-type

.header p span:nth-of-type(1) {
  color: red;
}

.header p span:nth-of-type(2) {
  color: blue;
}

.header p span:nth-of-type(3) {
  color: orange;
}
<div class="header">

  <p>
    <i class="fas fa-phone"></i>
    <span>444</span>
    <span>01</span>
    <span>34</span>
  </p>
</div>

答案 1 :(得分:3)

您要使用nth-of-typegeneral sibling combinator

span:nth-of-type(1) {
  color: red;
}

span:nth-of-type(2) {
  color: blue;
}

span:nth-of-type(3) {
  color: orange;
}
<div class="header">

  <p>
    <i class="fas fa-phone"></i>
    <span>444</span>
    <span>01</span>
    <span>34</span>
  </p>
</div>

span {
  color: green;
}

i ~ span {
  color: red;
}
<div class="header">

  <p>
    <span>Some span before the `i` tag.</span>
    <i class="fas fa-phone"></i>
    <span>444</span>
    <span>01</span>
    <span>34</span>
  </p>
  
  <span>Some span elsewhere in the document</span>
</div>

答案 2 :(得分:0)

这可能有用,它的i标签是这里的问题

div > span:nth-child(1) {
  color: red;
}

div > span:nth-child(2) {
  color: blue;
}

div > span:nth-child(3) {
  color: orange;
}
<div class="header">
  <p>
    <i class="fas fa-phone"></i>
    <div>
     <span>444</span>
     <span>01</span>
     <span>34</span>
    </div>
  </p>
</div>

相关问题