【问题标题】:How do I select the first class from a div in CSS? [duplicate]如何从 CSS 中的 div 中选择第一个类? [复制]
【发布时间】:2015-11-03 13:17:59
【问题描述】:

这是我的html代码:

<div class="role-main">
    <div class="abc">
    </div>
    <div class="bca">
    </div>
    <div class="test">
    </div>
    <div class="test">
    </div>
    <div class="test">
    </div>
</div>

这是css部分:

.role-maine .test:first-of-type {margin-left:0px}
.role-maine .test {margin-left:30px;}

所以我要为第一类分配 de margin-left:0px,它的名称为“test”?

【问题讨论】:

  • 这是网站:latesthoes.mediaswitch.ro。我说的是底部的 3 个 iphone 图片
  • 具体参考 BoltClock 在链接线程中的回答。

标签: html css


【解决方案1】:

你要找的选择器好像是:first-child,比如:

.role-main .test:first-child { margin-left: 0; }

在这种情况下并对其进行重构,您还可以这样做:

/* .role-main .test:first-of-type {margin-left:0px}
   Not needed anymore */
.role-main .test:not(:first-child) { margin-left: 30px; }

编辑:作为对 @Popnoodles 答案的补充,您命名的类确实不同。我的代码是固定的。

【讨论】:

  • 我已经试过了,还是不行
  • 那是因为他的代码中有错字。他的意思是这个代码.role-main .test:first-child { margin-left: 0; }
  • 我更新了我的代码。我看到了那个错误,但这不是问题。仍然无法正常工作:(
  • @AttilaNaghi 请注意浏览器缺乏:not() 支持,而不是:first-of-type 支持。
  • Kyrbi 感谢您的补充。正如我在编辑中通知的那样,@popnoodles 已经在他的帖子中注意到了这个错误。
【解决方案2】:

它不起作用,因为您的代码中有错字。你的 div 已经进入了 html 类 role-main 但在 CSS 中你称之为 .role-maine

【讨论】:

    【解决方案3】:

    这里只有 JS 解决方案可以帮助您。

    var el = document.getElementsByClassName('test')[0];
    el.style.marginLeft = "0px";
    

    http://jsfiddle.net/z0jbpnaq/

    这可能对大家都有帮助 - CSS select first element with a certain class

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 2016-11-26
      • 1970-01-01
      相关资源
      最近更新 更多