【问题标题】:Select children of nth-of-type选择第n个类型的孩子
【发布时间】:2013-11-12 04:41:09
【问题描述】:

我很难理解如何选择第 n 个类型选择的孩子。

我希望选择 .formdiv:nth-of-type(1) 的标签比使用 .formdiv 选择的所有其他 div 中的标签短

通过以下 jsfiddle 最容易解释:http://jsfiddle.net/LSjLT/1/

我需要包含 text1 和 text2 的标签的宽度小于包含较长文本的标签。

我发现特别奇怪的是,我编写的选择器在 jQuery 中运行良好(返回正确的节点),但在 css 中似乎不起作用:

.formdiv:nth-of-type(1) label{
    width: 60px;
}

我的html如下:

<form id="settings">
    <div class="formdiv">
        <label for ="text1">text1:</label>
        <input id="text1"></input>
        </br>   

        <label for = "text2">text2:</label>
        <input id="text2"></input>
        </br>   

        </br>   
    </div>
    <div class="formdiv">
        <label for = "longer text 1">longer text 1:</label>
        <input id="longer text 1"></input>
        </br>   

        <label for = "longer text 2">longer text 2:</label>
        <input id="longer text 2"></input>
        </br>   

        </br>   
    </div>
    <div class="formdiv">
        <label for = "longer text 1">longer text 1:</label>
        <input id="longer text 1"></input>
        </br>   

        <label for = "longer text 2">longer text 2:</label>
        <input id="longer text 2"></input>
        </br>   

        </br>   
    </div>
</form>

和我当前的 css:

#settings .formdiv label {
  font: 12px Arial;
  text-align: right;
  width: 80px;
  display: inline-block;

}

#settings input {
  display: inline-block;
}

.formdiv {
  display:inline-block;
}

/*This doesn't seem to work!*/
.formdiv:nth-of-type(1) label{
    width: 60px;
}

非常感谢您的帮助。

罗宾

【问题讨论】:

标签: html css css-selectors


【解决方案1】:

在.formdiv 和:nth-of-type(1) 之间添加一个空格

jsFiddle example

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

您选择了nth-of-type 或.formdiv。

添加空格会选择.formdiv 的子元素中的nth-of-type。

同样适用于.formdiv :first-of-type jsFiddle example

再次注意空格。

【讨论】:

  • 这不等于:first-child吗?你真的不想定位你所追求的标签吗?喜欢.formdiv label:nth-of-type(1) { color: red; }?
  • @Stigma 是的!你完全正确,我误读了这个问题。尽管如此,1+ 为您的解决方案。
  • 感谢您的帮助!
【解决方案2】:

选择器#settings .formdiv label{} 覆盖.formdiv:nth-of-type(1) label{},因为它有一个ID,并且它针对每个&lt;label&gt; 的width 属性

在.formdiv:nth-of-type(1) label 上添加#settings 元素以增加其specifcity:

#settings .formdiv:nth-of-type(1) label{
    width: 60px;
}

http://jsfiddle.net/LSjLT/12/

【讨论】:

  • 感谢您的回答和清晰的解释。你不会相信我在发布问题之前浪费了多少时间摆弄这个!
【解决方案3】:
.formdiv:nth-of-type(1) label{
width: 60px !important;
}

在 css 中使用 id 不是一个好习惯。在你的代码中添加这个,你可以看到结果。

【讨论】:

    【解决方案4】:

    使用以下内容:

    .formdiv:first-of-type input {css}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      • 2012-06-13
      • 2012-07-22
      • 2023-03-16
      • 2015-01-29
      • 2022-08-12
      • 1970-01-01
      相关资源
      最近更新 更多