【问题标题】:Complex CSS/LESS: Why doesn't this nth-child(even) ~ p work?复杂的 CSS/LESS:为什么这个 nth-child(even) ~ p 不起作用?
【发布时间】:2016-05-27 03:28:59
【问题描述】:

我正在尝试使用 nth-child(even) 制作交替模式,其中偶数元素及其各自的一般兄弟是红色的。

但是,经过一段时间的尝试,我无法弄清楚如何使“通用兄弟选择器”与交替颜色的元素具有相同的颜色......

这是一个sn-p:

h1:nth-child(even),
h1:nth-child(even) ~ p {
  color: red;
}
<h1>Section 1</h1>
<p>I am odd.</p>
<p>I am odd.</p>

    
<h1>Section 2</h1>
<p>I am even and I should be red.</p>
<p>I am even and I should be red.</p>

<h1>Section 1</h1>
<p>I am odd.</p>
<p>I am odd.</p>
    
<h1>Section 2</h1>
<p>I am even and I should be red.</p>
<p>I am even and I should be red.</p>

另外,这是 jsbin 中的一个示例: http://jsbin.com/tixobu/edit?html,css,output

这甚至可能吗?任何帮助或花絮将不胜感激!

谢谢

【问题讨论】:

    标签: html css less frontend


    【解决方案1】:

    你需要Adjacent sibling selectors而不是General sibling selectors

    h1:nth-child(even),
    h1:nth-child(even) + p, h1:nth-child(even) + p + p{
      color: red;
    }
    <h1>Section 1</h1>
    <p>I am odd.</p>
    <p>I am odd.</p>
    
        
    <h1>Section 2</h1>
    <p>I am even and I should be red.</p>
    <p>I am even and I should be red.</p>
    
    <h1>Section 1</h1>
    <p>I am odd.</p>
    <p>I am odd.</p>
        
    <h1>Section 2</h1>
    <p>I am even and I should be red.</p>
    <p>I am even and I should be red.</p>

    【讨论】:

    • 感谢您的快速回复!这在这种情况下肯定有效,但是如果有可变数量的

      标签怎么办?

    • 您可以将paragraphs 包装在div 中,然后改用h1:nth-child(even) + div
    • 正如@Jonathon 所说,最好的方法是将它们包装在 div 中,或者你可以只使用 JS。
    • 甜...就是这样!谢谢大家!!
    猜你喜欢
    • 2019-02-15
    • 2014-12-17
    • 1970-01-01
    • 2017-06-11
    • 2021-12-10
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多