首页 > 开发 > CSS > 正文

深入理解CSS 选择器

2024-07-11 08:37:32
字体:
来源:转载
供稿:网友

1. 选择器简介

◦【MDN】https://developer.mozilla.org/zh-CN/docs/Learn/CSS/Introduction_to_CSS/Selectors

  2. 选择器

◦简单选择器(Simple selectors):通过元素类型、class 或 id 匹配一个或多个元素,之所以这么称呼它是因为它们基于元素的类型(或其 class或 id)直接匹配文档的一个或多个元素。 ◦类型选择器(又名元素选择器)


<p>
  What color do you like?
</p>
<div>
  I like blue.
</div>

/* All p elements are red */
p {
color: red;
}

/* All div elements are blue */
div {
color: blue;
}

◦此选择器只是一个选择器名和指定的HTML元素名的不区分大小写的匹配。这是选择所有指定类型的最简单方式

◦类选择器


<ul>
<li class="first done">Create an HTML document</li>
<li class="second done">Create a CSS style sheet</li>
<li class="third">Link them all together</li>
</ul>

/* The element with the class "first" is bolded */
.first {
font-weight: bold;
}

/* All the elements with the class "done" are strike through */
.done {
text-decoration: line-through;
}

◦类选择器由一个点“.”以及类后面的类名组成。类名是在 HTML class 文档元素属性中没有空格的任何值
 

◦文档中的多个元素可以具有相同的类名,而单个元素可以有多个类名(以空格分开多个类名的形式书写)

◦ID 选择器


<p id="polite">
Good morning
</p>
<p id="rude">
Go away
</p>

#polite {
font-family: cursive;
}
#rude {
font-family: monospace;
text-transform: uppercase;
}

◦ID选择器由哈希/磅符号 (#)组成,后面是给定元素的ID名称

◦任何元素都可以使用 id 属性设置唯一的ID名称。 这是选择单个元素的最有效的方式

◦通用选择器


<div>
<p>I think the containing box just needed a <strong>border</strong> or <em>something</em>, but this is getting <strong>out of hand</strong>!</p>
</div>
* {
padding: 5px;
border: 1px solid black;
background: rgba(255,0,0,0.25)
}

◦通用选择(*)是最终的王牌。它允许选择在一个页面中的所有元素。
◦由于给每个元素应用同样的规则几乎没有什么实际价值,更常见的做法是与其他选择器结合使用

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表