【问题标题】:why marginTop not working in using nth-of-type? [duplicate]为什么 marginTop 在使用第 n 个类型时不起作用? [复制]
【发布时间】:2022-02-10 21:26:50
【问题描述】:

我已经使用 nth-of-type 添加了边距顶部,为什么它没有被应用?但是当我传递值 3 时它可以工作找到@为什么?

<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .rc105 .rc105-subheader:nth-of-type(2) {
      margin-top: 32px;
    }
    
  </style>
</head>
<body>
<section class="rc105 rc105v0" >
  <div class="cwidth">
    <div class="rc105-subheader">
      <div class="rc105-ttl">
         Applications
      </div>
      <p class="desc"> together.
        <a href="#" class="link">Learn more </a></p>
    </div>


    <div class="rc105w1 rw-scrim-neutral-40bg">
    </div>

    <div class="rc105-subheader">
      <div class="rc105-ttl">
        Test
      </div>
      <p class="desc"> platform.
        <a href="#" class="link">Learn</a></p>
    </div>

    <div class="rc105w1 rw-scrim-neutral-40bg">
    </div>

  </div>
</section>
</body>
</html>

【问题讨论】:

    标签: html css


    【解决方案1】:

    第 nth-of-type 指的是元素类型,在本例中为 div

    它不是指选择器中该类的第 n 个实例。

    这 3 个有效,因为您的目标类是该节点中的第三个 div。 2 不起作用,因为第二个 div 没有那个类,它有一些 rw-scrim-neutral-40bg 类。

    通常更常见的是在选择器中看到与元素一起使用的 nth-of-type,例如div:nth-of-type(#)p.something:nth-of-type(#)

    【讨论】:

    • 任何更好的选择第二个的解决方案rc105-subheader
    • 实在不行。您最好的选择是使用具有正确节点索引的 nth-child/nth-of-type;或者,使用某种相邻/兄弟选择器,例如.rc105-subheader + div + .rc105-subheader.rc105-subheader ~ .rc105-subheader 但它们也有自己的缺点。如果您可以使用 JavaScript,您可以循环遍历子标题并向其中添加另一个类或相应地对其进行样式设置。
    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2019-12-04
    • 2014-09-25
    • 2020-10-12
    • 2012-06-10
    相关资源
    最近更新 更多