CSS选择器

之前让AI帮我写了CSS,虽然用起来完全没问题,但我试着理解它。

选择器

1. 基础选择器

<div class="btn primary"></div>

类名可以有多个,用空格隔开,ID是唯一的,不能有多个ID,更不会用空格隔开。

2. 组合选择器

html
<h1>标题</h1>
<p>第一段</p>
<p>第二段</p>

css
h1 + p {    color: red;}

只有第一个p标签会变红。

<h1></h1>
<p>文本1</p>
<div></div>
<p>文本2</p>
<p>文本3</p>

位于 h1 后面的所有 p都被选中,包括文本2和文本3。

3. 属性选择器

包含某属性

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加上具体的标签 就可以匹配到。