【问题标题】:nth-of-type and nth-child in css not working properply [duplicate]css中的nth-of-type和nth-child无法正常工作[重复]
【发布时间】:2014-11-12 13:20:16
【问题描述】:

我想为第 n 个子标志应用绿色

<div id="axis">
     <div class="super"></div>
     <div class="flag">flag 1</div><!-- I want this text to be green-->
     <div class="super"></div>
     <div class="flag">flag 2</div>
     <div class="super"></div>
     <div class="flag">flag3</div>
     <div class="super"></div>
</div>

CSS:

#axis{
    color:red;
}

#axis .flag:nth-of-type(1){
    color:green;  
}

#axis .flag:nth-child(1){
    color:green;
}

我在这两种情况下都试过了,但都没有工作......

Fiddle

【问题讨论】:

  • 索引号为2。所以尝试使用2 而不是1
  • nt-childnt-of-type 不根据类或 ID 进行选择。
  • @MaryMelody - 你的答案是静态的
  • @JqueryKing 那你为什么要标记 jQuery?
  • jquery 用户也知道 css 为什么我被标记为 jquery

标签: html css css-selectors


【解决方案1】:

另一种方式DEMO

<ul id="axis">
    <li class="flag">flag 1</li>
    <li class="flag">flag 2</li>
    <li class="flag">flag3</li>
</ul>

.flag {
    list-style:none;
    color:red;
}


.flag:nth-of-type(1) {

    color:green;  
}

【讨论】:

    【解决方案2】:

    实现这一目标的另一种方法是

    <div id="axis">
        <div class="super"></div>
        <div class="flag">flag 1</div><!-- I want this text to be green-->
        <div class="super"></div>
        <div class="flag">flag 2</div>
        <div class="super"></div>
        <div class="flag">flag3</div>
        <div class="super"></div>
    </div>
    

    在 CSS 中是

    #axis > div:nth-child(2) {
        color: green;
    }
    

    另一种方式:

    应用通用 CSS:

    .flag {
       /* first .flag element styles here */
       /* though these styles are applied to all .flag elements, in later step they get overridden. */
    }
    
    .flag + .flag{
        /* override above styles */
        /* Applies css to all the .flag elements except the first one */
    }
    

    【讨论】:

    • 你的答案是静态的。假设 nth-child(2) 类是 super 意味着它也应用绿色而不是场景
    • @JqueryKing 因为,这篇文章被关闭了。我在这篇文章中将我的答案添加为“另一种方式”。 Abhijeet,我希望你没有被冒犯。
    • @Mr_Green 完全没有,我学到了一些东西,我为什么要被冒犯。
    • @Mr_Green - 但是,你的方法行不通。你想要通用的兄弟组合器~,而不是相邻的兄弟组合器+
    • @Alohci 两者的工作原理相同。因为我在这里没有使用:first-child 或其他特定的伪类。
    猜你喜欢
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多