【问题标题】:Making an image disappear with :nth-of-typen only works with (0) and (1)使用 :nth-of-type 使图像消失仅适用于 (0) 和 (1)
【发布时间】:2018-07-15 08:32:09
【问题描述】:

我刚刚在 Codecademy 上完成了顶点项目,但希望在进入较小的屏幕尺寸时让阅读日记的人消失。共有 3 个 img-holder div...我试过了,但它也删除了底部的图像...

 .supporting .img-holder:nth-of-type(0) {
      display: none;
    }
<div class="container supporting">
  <div class="img-holder">
  <img src="images/information-main.jpg">
    <div class="caption">
      <h2>It doesn't hurt to keep practicing</h2>
      <p>Lorem ipsusssm dolor sit amet, consectetur adipisicing elit. Id accusantium, optio est prribus!</p>
      <p id="signature">Emmanuel, Sr Strategist at Hiring.com</p>
    </div>
  </div>
</div>

我不明白为什么它在使用时不起作用 Live version is visible here

【问题讨论】:

  • 它是 1-indexed,0 不会匹配任何东西。

标签: html css css-selectors css-transitions


【解决方案1】:

:nth-of-type 根据其范围内的元素类型(例如div)选择元素。具有如下结构的含义:

div.supporting
  div.img-holder A
div.supporting
  div.img-holder B
div.supporting
  div.img-holder C

选择器.supporting .img-holder:nth-of-type(1) 选择所有三个。 A 是其父类型中的第一个 (div)。 B 也是其父级中的第一个类型。 C 也一样。

也许你想要.supporting:first-child .img-holder——这只会选择A。 (请注意,这仍然假设特定的 .supporting 是其容器的第一个子级。可能不是这样,并且有解决方法。解决它的最简单方法是为第一个 .supporting 设置一个特定的类, 如果它的行为方式不同。这将在没有复杂/难以理解/难以修改的选择器的情况下工作,并具有出色的浏览器支持。)

【讨论】:

    【解决方案2】:

    首先,nth-of-type1 索引而不是 0 。所以你应该从1开始。

    其次,nth-of-type 不选择类或 id。它选择元素的类型,例如div,p,img,h1等。没有nth-of-class选择器。

    您应该尝试根据您的 HTML 选择您的 div。所以你可以使用例如(在检查你的 html 结构之后)

    .supporting-1 + .supporting &gt; .img-holder { display:none }

    【讨论】:

    • 基于 HTML 结构的详细细节的选择器会导致糟糕的 CSS。结构中的微小变化(例如,在您的示例中在 .supporting-1.supporting 之间引入另一个元素)将破坏 CSS。恕我直言,最好有通用的、易于理解的类,并且尽可能不要使用更多“高级”选择器。
    • @Aurel Bílý:当然,除非你真的打算在引入这样的元素时破坏你的 CSS。没有理由仅仅为了避免使用组合器而引入一个独特的类,这样做是合乎逻辑的。
    • @BoltClock 当然,这取决于项目的上下文/范围。就 OP 而言,您认为哪一个是更好的选择?
    【解决方案3】:

    nth-of-type,匹配元素类型而不是元素类,因此您可以通过其 div 匹配它,并记住 css 中的第 n 个不是 0 索引基数是 1 索引基数,因此将第一个与 1 匹配

    .supporting div:nth-of-type(1) {
      display: none;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多