理解CSS | 青训营笔记

103 阅读3分钟

这是我参与「第四届青训营」笔记创作活动的第2天

在页面中使用CSS的三种方法

<!-- 1. 外链 -->
<link rel="stylesheet" href="/assets/style.css">
<!-- 2. 嵌入 -->
<style>
	li {margin: 0; list-style: none;}
	p {margin: lem 0;}
</style>
<!-- 3. 内联 -->
<p style="margin:lem 0">test</p>

推荐使用第一种导入方法,进行内容和样式的解耦。

如果使用组件开发的方式,如用vue开发也可以用第二种方式。

不推荐用内联方式。

CSS的工作方式

加载解析HTML后,会生成一个DOM树;

在加载解析CSS后,通过DOM树把样式添加到DOM节点,最后渲染生成页面。

选择器 Selector 的种类

  1. 通配 *
* {
  color: red;
}
  1. 按照标签名(无前缀)
  2. 按照类名(前缀.
  3. 按照id(前缀#
  4. 按照属性
<input disabled/>
<style>
 [disabled] {
	 background: #eee;
	 color: #999;
 }
</style>
  1. 按照标签和属性值
<input type="password"/>
<style>
input[type="password"] {
	...
}
</style>
  1. 按照标签和匹配的属性值
<a href="#123"/>
<a href="123.jpg"/>
<style>
a[href^="#"] {
	...
}
a[href$=".jpg"] {
	...
}
</style>
  1. 状态性伪类 (标签+状态)
a:hover {
	...
}
:focus {
	outline: 2px solid orange;
}
  1. 结构性伪类 (标签+DOM树中的位置)
li:first-child {
	color: coral;
}
li:last-child {
	border-bottom: none;
}
  1. 组合的方式
<input class="error"/>
<style>
	input.error {
		...
	}
</style>
名称语法说明示例
直接组合AB满足A的同时满足Binput:hover
后代组合A B选中B,如果它是A的子孙nav a
亲子组合A > B选中B,如果它是A的子元素section > p
兄弟选择器A ~ B选中B,如果它在A后且和A同级h2 ~ p
相邻选择器A + B选中B,如果它紧跟在A后面h2 + p
  1. 选择器组 (用逗号隔开)

颜色

color: rgb(12, 3, 4);
color: hsl(56, 78%, 9%);
color: green;
color: rgba(4, 3, 21, 0.5);
color: hsla(9, 87%, 65%, 1.0);
  1. RGB: Red(00~ff) Green(00~ff) Blue(00~ff)
  2. HSL: 色相Hue(0~360) 饱和度Saturation(0~100%) 亮度Lightness(0~100%)
  3. 直接指定: black white
  4. 透明度: alpha(0.00~1.00) rgba hsla

字体

font-family: Cursive, Serif;
font-size: small;
font-style: normal;

用逗号分隔指定不同字体族是为了兼容性

浏览器会从前往后和设备上安装的字体匹配

最好最后加上一个通用字体族

也可以在牺牲加载时间的情况下使用Web Fonts

建议中英文混排时将英文字体放在前面,方便英文优先匹配到英文字体

通用字体族

Serif衬线体
Sans-Serif无衬线体
Cursive手写体
Fantasy较夸张的字体
Monospace等宽字体

字体大小 font-size

  1. 关键字 small medium large
  2. 长度 px em em 是相对的单位
section {
	font-size: 20px;
}
section h1{
	font-size: 2em; // 2 * 20px
}
  1. 百分数:相对于父元素字体大小

字体风格 font-style

  1. normal
  2. italic
  3. bold

字重(粗细) font-weight

取值范围: 100 ~ 900

其中400相当于normal,700相当于bold

具体的实际效果视具体字体支持而定

行高 line-height

默认行高大概1.12,不太适合阅读,多行文本一般需要手动调整

white-space

normal默认显示
nowrap强制不换行
pre保留原始内容
pre-wrap自动换行
pre-line合并空格,保留换行

默认情况下,多个空行在显示时会被合并成一个,可以使用white-space属性

其他属性

text-align justify:可能对最后一行不生效

spacing letter-spacing word-spacing 字符或单词之间的间距

text-indent

text-decoration

以上属性都可以放到font一个属性里