前军教程网

中小站长与DIV+CSS网页布局开发技术人员的首选CSS学习平台

CSS 中的最后一个子级选择器与最后一个类型选择器

假设我们有以下 HTML:

<div>
    <h1>First h1</h1>
    <h1>Second h1</h1>
    <p>First paragraph</p>
    <p>Second paragraph</p>
</div>

如果我们想定位 div 的最后一个子元素,我们将使用:

div :last-child {
  color: red;
}
/*note the white space between div and :last-child*/

如果我们只想定位 div 的最后一个子元素(仅当该子元素是一个p元素时),那么我们将拥有:

div p:last-child {
  color: red;
}

另一方面,last-of-type将定位该类型元素的最后一次出现。因此,假设我们要定位h1div 中最后一次出现的元素:

div h1:last-of-type {
  color: blue;
}

不一定last-of-type是最后一个孩子。

这些选择器还有许多补充替代方案,例如 : 、:first-of-type等。:nth-last-of-typefirst-child

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言