常见的css选择器

本文介绍了CSS中后代选择器、子元素选择器、相邻兄弟选择器、选择器分组、类选择器和属性选择器的使用方法,帮助读者理解并记忆常见的CSS选择器技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于css中的类选择器用法较多,时间长了,总是容易遗忘,因此对这部分内容做了一些简单的总结

一、后代选择器

<html>
<head>
<style type="text/css">
ul em {color:red; font-weight:bold;}
</style>
</head>

<body>
<ul>
  <li>List item 1
    <ol>
      <li>List item 1-1</li>
      <li>List item 1-2</li>
      <li>List item 1-3
        <ol>
          <li>List item 1-3-1</li>
          <li>List item <em>1-3-2</em></li>
          <li>List item 1-3-3</li>
        </ol>
      </li>
    </ol>
  </li>
</ul>
</body>
</html>

在这里插入图片描述
后代选择器中的后代可以是多层次的深层嵌套,选择器之间用空格连接

二、子元素选择器

<html>
<head>
<style type="text/css">
h1 > strong {color:red;}
</style>
</head>

<body>
<h1>This is <strong>very</strong> <strong>very</strong> important.</h1>
<h1>This is <em>really <strong>very</strong></em> important.</h1>
</body>
</html>

相比于后代选择器,子元素选择器只能选择父元素中的一代子元素,选择器之间用>连接,可以存在空格

三、相邻兄弟选择器

<html>
<head>
<style type="text/css">
p + li {font-weight:bold;}
</style>
</head>

<body>
<div>
  <ul>
    <p>List item 1</p>
    <li>List item 2</li>
    <li>List item 3</li>
  </ul>
</div>
</body>
</html>

在这里插入图片描述
选择紧接在另一个元素后的元素,而且二者有相同的父元素,此时可以使用相邻兄弟选择器。选择器之间用+连接,可以存在空格

四、选择器分组

<html>
<head>
<style type="text/css">
h1, h2, h3, h4, h5, h6 {color:blue;}
</style>
</head>

<body>
<h1>这是 heading 1</h1>
<h2>这是 heading 2</h2>
<h3>这是 heading 3</h3>
</body>
</html>

在这里插入图片描述
选择器之间用逗号隔开,可以没有空格,并不影响

五、类选择器

<html>
<head>
<style type="text/css">
p.important {color:red;}
h1.important {color:blue;}
</style>
</head>

<body>
<h1 class="important">This heading is very important.</h1>

<p class="important">This paragraph is very important.</p>

<p>This is a paragraph.</p>

</body>
</html>

在这里插入图片描述
类选择器可以结合元素选择器一起使用,二者之间不能存在空格,否则会变成后代选择

六、属性选择器

<html>
<head>
<style type="text/css">
[title]
{
color:red;
}
</style>
</head>

<body>
<h2 title="Hello world">Hello world</h2>
<hr />
<h2>Hello world</h2>
</body>
</html>

在这里插入图片描述
属性选择器可以根据元素的属性及属性值来选择元素,该选择器还可以搭配子串匹配进行使用
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值