CSS 基础知识笔记 - 第3天
CSS 选择器
CSS 提供了多种选择器用于定位 HTML 元素:
基础选择器
标签选择器
类选择器
1 2 3 4
| .box { width: 100px; height: 100px; }
|
ID 选择器
1 2 3
| #header { height: 80px; }
|
通配符选择器
1 2 3 4
| * { margin: 0; padding: 0; }
|
字体样式
字体大小
1 2 3 4 5
| p { font-size: 16px; font-size: 1.2em; font-size: 1.2rem; }
|
字体粗细
1 2 3 4 5
| p { font-weight: normal; font-weight: bold; font-weight: 400; }
|
字体倾斜
1 2 3 4
| p { font-style: normal; font-style: italic; }
|
行高
1 2 3 4 5
| p { line-height: 1.5; line-height: 24px; line-height: 150%; }
|
小技巧:利用行高设置垂直居中效果(单行文本)
1 2 3 4
| .box { height: 100px; line-height: 100px; }
|
字体族
1 2 3
| body { font-family: "Microsoft YaHei", Arial, sans-serif; }
|
常用字体族:
- 衬线字体(serif):如 Times New Roman
- 无衬线字体(sans-serif):如 Arial、Helvetica
- 等宽字体(monospace):如 Courier New
- 草书字体(cursive)
- 幻想字体(fantasy)
font 复合属性
1 2 3 4
| p { font: italic bold 16px/1.5 "Microsoft YaHei", sans-serif; }
|
注意:
- font-size 和 font-family 是必须的
- 其他属性如果不指定则使用默认值
文本样式
文本缩进
1 2 3
| p { text-indent: 2em; }
|
文本对齐
1 2 3 4 5 6
| p { text-align: left; text-align: center; text-align: right; text-align: justify; }
|
修饰线
1 2 3 4 5 6
| p { text-decoration: none; text-decoration: underline; text-decoration: overline; text-decoration: line-through; }
|
文本转换
1 2 3 4 5 6
| p { text-transform: none; text-transform: uppercase; text-transform: lowercase; text-transform: capitalize; }
|
字母间距和单词间距
1 2 3 4
| p { letter-spacing: 2px; word-spacing: 5px; }
|
文本颜色
1 2 3 4 5 6
| p { color: red; color: #ff0000; color: rgb(255,0,0); color: rgba(255,0,0,0.5); }
|
背景样式
背景颜色
1 2 3
| div { background-color: #f5f5f5; }
|
背景图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| div { background-image: url('image.jpg'); background-repeat: repeat; background-repeat: no-repeat; background-repeat: repeat-x; background-repeat: repeat-y; background-position: center center; background-position: 50% 50%; background-position: 100px 200px; background-size: cover; background-size: contain; background-size: 100% 100%; background-attachment: scroll; background-attachment: fixed; }
|
background 复合属性
1 2 3 4
| div { background: #f5f5f5 url('image.jpg') no-repeat fixed center/cover; }
|
CSS 显示模式
块级元素
- 独占一行,可设置宽高
- 例如:div, p, h1-h6, ul, li, dl, dt, dd, form, header, nav, footer
行内元素
- 一行可显示多个,宽高由内容决定
- 例如:span, a, b, strong, i, em, del, ins
行内块元素
- 一行可显示多个,可以设置宽高
- 例如:img, input, button, textarea, select
修改显示模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| span { display: block; }
div { display: inline; }
div { display: inline-block; }
div { display: none; }
|
CSS 特性
层叠性
继承性
- 子元素会继承父元素的某些样式,如文字颜色、字体大小等
- 一般与文字相关的属性会被继承
优先级
- !important > 行内样式 > ID选择器 > 类选择器 > 标签选择器 > 通配符 > 继承
- 权重计算:(行内样式, ID选择器个数, 类选择器个数, 标签选择器个数)
- 例如:#nav .list li 的权重为 (0, 1, 1, 1),大于 .nav p 的权重 (0, 0, 1, 1)