【问题标题】:CSS select first element with a certain classCSS选择具有特定类的第一个元素
【发布时间】:2011-07-14 07:44:55
【问题描述】:

选择某个类的第一个元素的语法是什么?请说明该选择方法是 CSS3 还是 CSS2.1 的一部分。

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    如果您需要在其兄弟姐妹中具有某个类的第一个元素,您可以使用

    .myclass {
        /* styles of the first one */
    }
    
    .myclass ~ .myclass {
        /* styles of the others (must cancel the styles of the first rule) */
    }
    

    不要尝试仅在一个规则中使用.myclass:not(.myclass ~ .myclass) 来执行此操作,因为:not() 只接受括号中的简单选择器,所以它不起作用。

    如果你想要整个文档中的第一个.myclass,没有办法单独使用CSS。

    发布的:nth-of-type():nth-child() 方法是错误的,即使它们碰巧与您页面中所需的元素相匹配。

    兄弟选择器 (~) 的浏览器支持:IE7+ 和所有其他。

    【讨论】:

    • 浏览器支持实际上比 CSS 结构伪类更好。编辑了我的答案以包含它。
    • 让我失望...我只是意识到我在您发布此内容后的一段时间内自己想到了这一点,完全忘记了您的答案。我现在把你的功劳归功于你:stackoverflow.com/questions/2717480/…
    • 你知道同一个类的最后一个元素吗?
    【解决方案2】:

    这个问题和解决方案一样糟糕。 IMO 你应该以编程方式给第一个元素一个.first{} 类。

    【讨论】:

      【解决方案3】:

      试试这个

      .testparent .test:first-child {
          color: red;
      }
      
      <div class="testparent">
      <div class="test">test</div>
      <div class="test">test</div>
      <div class="test">test</div>
      </div>
      

      第一个 div 'test' 只有红色。

      【讨论】:

      • 嗯,不,匹配每个.test 的第一个p
      • 如果第一个孩子没有.test,但其他兄弟有,那么什么都不会被选中。
      • @ngduc 它使用类名而不是元素类型对我有用。谢谢
      【解决方案4】:
      .class-name:first-of-type {
        ⋮ declarations
      }
      

      【讨论】:

      猜你喜欢
      • 2011-02-12
      • 2011-10-31
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多