这是我参与「第四届青训营」笔记创作活动的第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 的种类
- 通配 *
* {
color: red;
}
- 按照标签名(无前缀)
- 按照类名(前缀
.) - 按照id(前缀
#) - 按照属性
<input disabled/>
<style>
[disabled] {
background: #eee;
color: #999;
}
</style>
- 按照标签和属性值
<input type="password"/>
<style>
input[type="password"] {
...
}
</style>
- 按照标签和匹配的属性值
<a href="#123"/>
<a href="123.jpg"/>
<style>
a[href^="#"] {
...
}
a[href$=".jpg"] {
...
}
</style>
- 状态性伪类 (标签+状态)
a:hover {
...
}
:focus {
outline: 2px solid orange;
}
- 结构性伪类 (标签+DOM树中的位置)
li:first-child {
color: coral;
}
li:last-child {
border-bottom: none;
}
- 组合的方式
<input class="error"/>
<style>
input.error {
...
}
</style>
| 名称 | 语法 | 说明 | 示例 |
|---|---|---|---|
| 直接组合 | AB | 满足A的同时满足B | input: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 |
- 选择器组 (用逗号隔开)
颜色
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);
- RGB:
Red(00~ff)Green(00~ff)Blue(00~ff) - HSL:
色相Hue(0~360)饱和度Saturation(0~100%)亮度Lightness(0~100%) - 直接指定:
blackwhite - 透明度: alpha(0.00~1.00)
rgbahsla
字体
font-family: Cursive, Serif;
font-size: small;
font-style: normal;
用逗号分隔指定不同字体族是为了兼容性
浏览器会从前往后和设备上安装的字体匹配
最好最后加上一个通用字体族
也可以在牺牲加载时间的情况下使用Web Fonts
建议中英文混排时将英文字体放在前面,方便英文优先匹配到英文字体
通用字体族
| Serif | 衬线体 |
| Sans-Serif | 无衬线体 |
| Cursive | 手写体 |
| Fantasy | 较夸张的字体 |
| Monospace | 等宽字体 |
字体大小 font-size
- 关键字
smallmediumlarge - 长度
pxemem 是相对的单位
section {
font-size: 20px;
}
section h1{
font-size: 2em; // 2 * 20px
}
- 百分数:相对于父元素字体大小
字体风格 font-style
- normal
- italic
- 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一个属性里