CSS last-of-type

CSS last-of-type

在CSS中,:last-of-type 伪类选择器用于选择某个元素的最后一个特定类型的子元素。这个选择器非常有用,可以帮助我们在样式设计中更精确地控制元素的样式。

语法

:last-of-type 伪类选择器的语法如下:

selector:last-of-type {
  /* styles */
}

其中 selector 是要选择的元素的父元素,:last-of-type 表示选择该父元素下的最后一个特定类型的子元素。

示例代码

示例1:选择最后一个段落元素

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS last-of-type Example</title>
<style>
p:last-of-type {
  color: red;
}
</style>
</head>
<body>
<p>geek-docs.com 1</p>
<p>geek-docs.com 2</p>
<p>geek-docs.com 3</p>
</body>
</html>

Output:

CSS last-of-type

在这个示例中,我们选择了最后一个段萼元素,并将其文字颜色设置为红色。

示例2:选择最后一个列表项

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS last-of-type Example</title>
<style>
li:last-of-type {
  font-weight: bold;
}
</style>
</head>
<body>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
</body>
</html>

Output:

CSS last-of-type

在这个示例中,我们选择了最后一个列表项,并将其字体加粗。

注意事项

  • :last-of-type 伪类选择器只能选择同级元素中的最后一个特定类型的子元素,不能选择父元素的最后一个子元素。
  • 如果没有符合条件的元素,:last-of-type 伪类选择器将不会生效。

总结

通过 :last-of-type 伪类选择器,我们可以方便地选择某个元素的最后一个特定类型的子元素,并对其进行样式设置。这个选择器在实际开发中非常有用,可以帮助我们更精确地控制页面元素的样式。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程