这是我参与「第五届青训营 」伴学笔记创作活动的第 2 天
走进CSS
CSS是什么?
- Cascading Style Sheets 层叠样式表
- 用于定义页面元素的样式
- 构成:选择器Selector、声明Declaration(属性Property:属性值Value)
- 页面中使用:外链、嵌入、内联
选择器selector
找出页面中的元素,以便给他们设置样式
多种选择器
-
通配选择器、标签选择器、id选择器、类选择器
-
属性选择器
<style>
[disabled]{
color:#999;
}
input[type="password"]{
color: red;
}
a[href^="#"]{ /* ^以"#"开头 */
color:#999;
}
a[href$=".jpg"]{ /* $以".jpg"结尾 */
color: red;
}
</style>
<body>
<label>用户名:<input value="dede" disabled /></label>
<label>密码:<input value="12345" type="password" /></label>
<p><a href="#top">回到顶部</a></p>
<p><a href="a.jpg">查看图片</a></p>
</body>
- 伪类(pseudo-classes)选择器
- 不基于标签和属性定位元素
- 状态性伪类,如
<a>的几种状态:link, visited, hover, active - 结构性伪类,根据DOM节点在DOM树中出现的相对位置来选定,如
first-child,last=child
- 选择器的组合
- 选择器组:用逗号分隔,如
[type="radio"],[type='checkbox']{color: red}
颜色color
- RGB三原色
rgb(143, 172, 135)#8fac87
- HSL
- 色相Hue,0-360
- 饱和度Saturation,0-100%
- 亮度Lightness,0-100%
hsl(18,66%,55%)- 使用场景:同一色相下需要调整亮度和饱和度,如按钮点击时的颜色变化
- 关键字:red, pink
- alpha不透明度
- 0-1,1为不透明
#ff0000ff,rgba(255,0,0,1),hsla(0,100%,50%,1)
字体font
- font-family
- 通用字体族:在设置字体时,最后一项最好加上通用字体族,确保之前字体识别不出来时,同一个字体族内的字体差别不会太大
- 中英文混排的场景下,建议英文字体写在前面,更好区分中英文字体
- 使用 Web Fonts:使用url,但会增加性能开销;中文字体,字体包一般比较大,需要先做裁剪
- font-size:单位:px, em, %等
- font-style 字体样式
- font-weight 字重(100-900),并非所有字体都有这么多自重
- line-height 行高,不加单位表示字体大小的倍数
- font: style weight size/height family
h1{font: bold 14px/1.7 Helvetica, sans-serif;}
深入CSS
- 选择器的优先级:特异度(Specificity)
- 继承,显示继承
inherit - 初始值,
initial
求值过程
布局
-
盒模型:width, height, padding, border, margin
-
box-sizing
常规流/文档流 Normal Flow
除了根元素、浮动和绝对定位外,其余元素都在常规流内(in-flow)
常规流的盒子,在某种排版上下文中参与布局:行级、块级、Table、FlexBox、Grid
行级排版上下文
- Inline Formatting Context(IFC)
- 只包含行级盒子的容器会创建一个IFC
- IFC排版规则
- 盒子在一行内水平拜访,一行放不下则换行显示
- text-align 水平对齐
- vertival-align 垂直对齐
- 避开浮动元素
块级排版上下文
- Block Formatting Context(BFC)
- 创建BFC的容器
- 根元素
- 浮动、绝对定位、inline-block
- Flex子项和Grid子项
- overflow值不为visible的块盒
- display: flow-root;
- BFC排版规则
- 盒子从上到下摆放
- 垂直margin合并
- BFC内盒子的margin不会与外面的合并
- BFC不会和浮动元素重叠
Flex Box
-
display: flex
-
flex-direction: row/row-reverse/column/column-reverse
-
主轴:justify-content
-
侧轴:align-items
-
Flexibility:设置子项的弹性(合并写法flex)
- flex-grow 有剩余空间的伸展能力
- flex-shrink 空间不足时的收缩能力
- flex-basis 基础长度
.container {
display: flex;
}
.a, .b, .c {
width:100px;
}
.a {
flex-grow: 2; /* 把分配剩余的空间中的的2份(2/3)分给a */
}
.b {
flex-grow: 1; /* 并非a的大小就是b的两倍 */
}
Grid
- display: grid
- grid-template-columns/rows
- grid line网格线
.a {
grid-row-start: 1;
grid-column-start: 1;
grid-row-end: 3;
grid-column-end: 3;
}
.a {
grid-area: 1/1/3/3;
}
浮动Float
- 元素脱离常规流,浮起来
- float: left
绝对定位
position 属性
- static 默认值,非定位元素
- relative 相对于自身位置进行偏移,不脱离常规流
- absolute 相对于最近的非static祖先定位,脱离常规流
- fixed 相对于视口的绝对定位,脱离常规流