CSS选择器
之前让AI帮我写了CSS,虽然用起来完全没问题,但我试着理解它。
选择器
1. 基础选择器
- 元素(标签)选择器:匹配所有指定标签,如
div、p。 - 类选择器:匹配指定 class,如
.container。 - ID 选择器:匹配指定 id,如
#header。 - 通用选择器:匹配所有元素,
*。
<div class="btn primary"></div>
类名可以有多个,用空格隔开,ID是唯一的,不能有多个ID,更不会用空格隔开。
2. 组合选择器
- 后代选择器:空格分隔,匹配所有子孙,如
div p。 - 子元素选择器:
>,只匹配直接子元素,如ul > li。 - 紧邻兄弟选择器:
+,匹配紧邻的下一个兄弟,如h1 + p。只匹配第一个符合条件的元素。
html
<h1>标题</h1>
<p>第一段</p>
<p>第二段</p>
css
h1 + p { color: red;}
只有第一个p标签会变红。
- 通用兄弟选择器:
~,匹配同一父元素下后续所有兄弟,如h1 ~ p。匹配所有和h1同级的所有p,不管中间隔了多少其他元素。
<h1></h1>
<p>文本1</p>
<div></div>
<p>文本2</p>
<p>文本3</p>
位于 h1 后面的所有 p都被选中,包括文本2和文本3。
3. 属性选择器
[attr]:包含某属性[attr=value]:属性等于某值[attr~=value]:属性值包含某单词[attr|=value]:属性值以指定值开头[attr^=value]:属性值以指定值开头[attr$=value]:属性值以指定值结尾[attr*=value]:属性值包含指定字符串
包含某属性
HTML
<input type="text">
<input>
<input type="password">
CSS
input[type] {
border: 2px solid red;
}
属性等于某值
input[type="password"] { background-color: yellow;}
只匹配 <input type="password">
4. 伪类选择器
伪类选择器,选择的是已经存在的元素的特定条件(状态,位置等)。只有触发特定条件的时候才会被选中。
/* 鼠标悬停状态 */
a:hover {
color: red;
}
/* 第一个子元素 */
li:first-child {
font-weight: bold;
}
/* 表单输入为空时 */
input:placeholder-shown {
border: 1px solid gray;
}
仍然作用于已有元素之上。
5. 伪元素选择器
伪元素/虚拟元素选择器,创建或选中元素内部的虚拟内容,让你可以样式化它。
/* 在每个段落前插入内容 */
p::before {
content: "★ ";
color: gold;
}
/* 段落的首字母放大 */
p::first-letter {
font-size: 32px;
font-weight: bold;
}
/* 段落首行样式 */
p::first-line {
text-transform: uppercase;
}
多个选择器可以同时应用某一个样式,如 h1, h2, h3 { color: red; }
观察
在了解选择器之后,我们可以看到,这段我实际使用的CSS代码(完全由AI提供),其实选择器是冗余的。
#post ul,#post ol,
.post ul,.post ol,
article ul,article ol,
.h-entry ul,.h-entry ol{
margin:1.2em 0;
padding-left:1.8em;
}
#post li,.post li,
article li,.h-entry li{
margin:.45em 0;
line-height:1.85;
color:#dbe4ee;
}
#post li::marker,
.post li::marker,
article li::marker,
.h-entry li::marker{
color:#6cf2ff;
}
/* ---------- hr ---------- */
#post hr,.post hr,
article hr,.h-entry hr{
border:0;
height:1px;
margin:2.8em 0;
background:linear-gradient(
to right,
transparent,
rgba(108,242,255,.55),
transparent
);
}
/* ---------- strong ---------- */
#post strong,.post strong,
article strong,.h-entry strong{
color:#ffffff;
font-weight:700;
}
/* ---------- table ---------- */
#post table,.post table,
article table,.h-entry table{
width:100%;
border-collapse:collapse;
margin:1.6em 0;
overflow:hidden;
border-radius:16px;
background:#0f1324;
}
大量的重复选择器,id选择器#post,类选择器.post,article标签 和 类选择器.h-entry 。在实际上WriteFrelly页面代码中,似乎没有.post ,好像只需要一条article加上具体的标签 就可以匹配到。