【问题标题】:Last-child not working with classes. Last-of-type also not working [duplicate]最后一个孩子没有上课。最后一种类型也不起作用[重复]
【发布时间】:2017-03-07 10:54:48
【问题描述】:

我正在尝试在我的 style.css 文件中选择一系列 wordpress 帖子(具有相同类)的 :last-child。 这是我的文档结构的简化版本:

<div id="container">
    <div id="content">
  <!--start .post-->
  <div id="post-33" class="hentry p1 post">
            <h2 class="entry-title"><a href="url">Post 1</a></h2>
            <div class="entry-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
        </div>
  <!--end  .post -->
  <!--start .post-->
  <div id="post-24" class="hentry p1 post">
    <h2 class="entry-title"><a href="url">Post 2</a></h2>
    <div class="entry-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </div>
  <!--end  .post -->
  <!--start .post-->
  <div id="post-24" class="hentry p1 post">
    <h2 class="entry-title"><a href="url">Post 3</a></h2>
    <div class="entry-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </div>
  <!--end  .post -->

        <div id="nav-below" class="navigation">
            <div class="nav-previous"></div>
            <div class="nav-next"></div>
        </div>
    </div><!-- #content -->
</div><!-- #container -->

我已经尝试过了,虽然它适用于 :first-child 选择器,但它根本不适用于 :last-child。

.post .entry-content { 
    background-color: pink; 
    border-bottom: 2px solid;
}

.post:first-child .entry-content { 
    background-color: red; 
    border-bottom: 0px solid;
}

.post:last-child .entry-content { 
    background-color: yellow; 
    border-bottom: 0px solid;
}

有什么想法吗? 这是我网站的实时版本:http://dev.visualvisual.com/

【问题讨论】:

  • post 类的最后一个元素不是其父级的最后一个子元素;并且没有last-of-class 伪类选择器。

标签: css wordpress css-selectors


【解决方案1】:

使用nth-of-typenth-last-of-type

.post:nth-of-type(1) .entry-content { 
    background-color: red; 
    border-bottom: 0px solid;
}

.post:nth-last-of-type(2) .entry-content { 
    background-color: yellow; 
    border-bottom: 0px solid;
}

first-childlast-child,顾名思义,用于对子元素进行操作,因此您可能希望使用#content:last-child 来查找最后一个元素(但不一定是.post)。

Codepen

【讨论】:

  • 这行不通,:last-of-type 不查看元素的类名,只查看其“标签名”。
  • 谢谢托梅克。谢谢,但它没有用......结果相同: :first-of-type 有效,但 :last-of-type 无效。
  • 你是对的,对不起。我更正了我的答案。
  • 谢谢托梅克。 nth-of-type 和 nth--of-type 完成了这项工作。非常感谢。
  • 很高兴我能帮上忙 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多