
css该如何选择元素呢?下面我们来看一下css选择元素的方法。
css可以使用:nth-of-type(n)选择器或:last-child选择器来选择元素。:nth-of-type(n)选择器匹配同类型中的第n个同级兄弟元素。:last-child选择器匹配属于其父元素的最后一个子元素的每个元素。
使用:nth-of-type选择器选择元素示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
p:nth-of-type(2)
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>
</body>
</html>效果图:

使用last-child选择器选择元素示例:
<!DOCTYPE html>
<html>
<head>
<style>
p:last-child
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>这是标题</h1>
<p>第一个段落。</p>
<p>第二个段落。</p>
<p>第三个段落。</p>
<p>第四个段落。</p>
<p>第五个段落。</p>
</body>
</html>效果图:

以上就是css如何选择元素?的详细内容,更多请关注易知道|edz.cc其它相关文章!














