CSS 选择器是一种用于查找和选择 HTML 元素的方法。它可以让你选择特定的 HTML 元素,从而对其进行样式定义和操作。要选择一个元素,可以使用 :last-child 选择器。
使用 :last-child 选择器
:last-child 选择器用于选择父元素的一个子元素。它可以用于任何 HTML 元素,包括 div、span、ul、li 等。
// 选择 ul 中的一个 li 元素 ul li:last-child { color: red; }
上面的代码将 ul 中的一个 li 元素的文字颜色设置为红色。
使用 :last-of-type 选择器
:last-of-type 选择器用于选择同类型的一个元素。例如,如果你有一个 div 元素,其中包含多个 p 元素,你可以使用 :last-of-type 选择器来选择一个 p 元素。
// 选择 div 中的一个 p 元素 div p:last-of-type { color: blue; }
上面的代码将 div 中的一个 p 元素的文字颜色设置为蓝色。
使用 :last-child 和 :last-of-type 的区别
在使用 :last-child 和 :last-of-type 选择器时,要注意它们的区别。:last-child 选择器只会选择父元素的一个子元素,而 :last-of-type 选择器会选择同类型的一个元素。
- 使用 :last-child 选择器可以选择父元素的一个子元素。
- 使用 :last-of-type 选择器可以选择同类型的一个元素。