【问题标题】:Style first element with class使用类样式化第一个元素
【发布时间】:2014-07-18 08:35:08
【问题描述】:

有没有办法只为具有特定类的第一个元素设置样式? :first-child 伪选择器似乎只适用于标签。

编辑:并非所有类都具有相同的父元素,因此 :first-child 不是一个选项。

【问题讨论】:

    标签: html css less


    【解决方案1】:

    你可以这样尝试:

    <div>
        <p class="blue">1st</p>
        <div class="blue">2nd</div>
    </div>
    <div>
        <div class="blue">3rd</p>
        <div class="blue">4th</div>
    </div>
    

    所以这只会使第一个元素为蓝色

    同时检查:first-child pseudo-class

    :first-child 伪类匹配第一个元素 其他元素的子元素。

    【讨论】:

      【解决方案2】:

      .class-name:nth-of-type(1)

      这应该是你想要的样式

      JsFiddle example

      【讨论】:

        【解决方案3】:

        这应该可以.classNamep:first-of-type

        【讨论】:

          【解决方案4】:

          您需要仔细检查您的班级名称。可能会出现拼写错误。

          看到这个fiddle。它向您展示了 :first-child 甚至可以与类选择器一起使用。 :)

          代码:

          <span class="spana">first</span>
          <span class="spana">second</span>
          
          .spana:first-child {
              background-color: #ddd;
          }
          

          【讨论】:

            【解决方案5】:

            使用nth-child() 伪类选择器是一个不错的方法,所有主流浏览器都支持这一点,包括IE9+。

            这是 HTML 示例:

            <div class="blue">Will be blue</div>    
            <div class="blue">Will not be blue</div>
            <div class="blue">Will not be blue</div>
            <div class="blue">Will not be blue</div>
            

            还有 CSS:

            .blue:nth-child(1) {
                color: blue;
            }
            

            这将选择类名blue 的第一个div。请记住,第一次迭代是通过将 1 传递给伪类来选择的,而不是 0 之类的数组。

            nth-child() 伪类还有其他关键特性;除了像我之前展示的那样传递数字外,伪类还支持诸如evenodd之类的关键字。

            //Applies styling to every even instance of the class .blue 
            .blue:nth-child(even) {
                color: blue;
            }
            
            //Applies styling to every odd instance of the class .blue 
            .blue:nth-child(odd) {
                color: blue;
            }
            

            这也可以更进一步;一个公式可以准确地表示样式要应用于哪些元素。 公式表示为an+b,其中a是要选择的元素的频率,b是偏移量。因此,公式3n+4 将样式应用于第四个元素,以及除此之外的每第三个元素。 (4、7、10、13、16 等...)。以下是如何应用此功能的示例。

            //Style every 6th instance of the class .blue, starting with the second element. (2, 8, 14, 20, 26).
            .blue:nth-child(6n+2) {
                color: blue;
            }
            

            如果不需要偏移量,则只需传入与之前相同的公式,在末尾删除偏移量;传入4n 就是一个例子。

            希望对你有帮助,我觉得这个伪类非常强大,同样被很多人低估了。

            【讨论】:

              【解决方案6】:

              没有一流的选择器。

              查看 BoltClock 的回答 (CSS3 selector :first-of-type with class name?)

              有一种解决方法,但对我不起作用

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2020-12-17
                • 2021-04-25
                • 2015-08-31
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多