「这是我参与2022首次更文挑战的第21天,活动详情查看:2022首次更文挑战」
前言
本来想直接写双栏布局的,但突然看到了一些别的内容,顺便也写上吧,主要是一些css方面的东西和一个编写懒加载需要用到的东西,之前写过一个懒加载的文章,这里再做一些小补充了就当。
写css性能提升的点
- 尽量不要使用那些消耗性能多的属性:浮动、定位等等。
- 当某些属性的值为0时不写单位,当某些属性值为0.几的时候0可以省略
- 尽量少的使用组合属性,比如margin:* * * *,分开写成margin-top、margin-bottom、margin-left、margin-right
- 使用link代替@import,因为link加载的比@import时间点早
- 尽量少使用标签选择器
- 选择器深度尽量不要超过三层
- 使用精灵图(sprites),减少http请求
判断可视区域常用到的一些属性
| 标题 | 意义 |
|---|---|
| window.innerHeigh | 浏览器可视区域的高度 |
| document.body.scrollTop、document.documentElement.scrollTop | 滚动条已经卷起的高度 |
| img.offsetTop | img标签距离文档流顶部的高度 |
| img.offsetTop<window.innerHeight+document.body.scrollTop | img标签到达了可视区 |
z-index
- 使用z-index的时候,元素的position属性必须为relative、absolute、fixed中的一种
- 父元素的position属性不能是relative
- 使用z-index的元素不能使用浮动
实现两栏布局的方法
这里说的两栏布局是指左边固定宽度,右边自适应宽度
- 左边做左浮动,右边设置margin-left,宽度设置为auto
.parent {
height: 100px;
}
.box1 {
width: 200px;
height: 100px;
background: tomato;
float: left;
}
.box2 {
height: 100px;
margin-left: 200px;
background: gold;
width:auto;//可以不设置,因为默认为auto
}
- 依旧是左边做左浮动,右边利用BFC特性,右边设置overflow:hidden
.parent {
height: 100px;
}
.box1 {
width: 200px;
height: 100px;
background: tomato;
float: left;
}
.box2 {
height: 100px;
background: red;
overflow: hidden;
}
- 父元素设置position:relative,左侧设置绝对定位,右侧设置margin-left
.parent {
height: 100px;
position: relative;
}
.box1 {
width: 200px;
height: 100px;
background: tomato;
position: absolute;
}
.box2 {
height: 100px;
background: red;
margin-left: 200px;
}
- 和上面的方法相反,右侧设置绝对定位
.parent {
height: 100px;
position: relative;
}
.box1 {
width: 200px;
height: 100px;
background: tomato;
}
.box2 {
height: 100px;
background: red;
position: absolute;
top: 0;
left: 200px;
bottom: 0;
right: 0;
}
- 父元素设置display:flex,左边设置固定宽度,右边设置flex:1(最常用),这里顺便提一下flex:1的含义,就是说项目会根据可用空间的大小来变大,flex是flex-grow、flex-shrink、flex-basis的简写,如果flex后只写了一个值,并且是数字那就是代表flex-grow,如果是两个值切都是数字,那代表的是flex-grow、flex-shrink,如果是一个值但是是em,px,那表示的是flex-basis,如果是三个值那就是flex-grow,flex-shrink,flex-basis
.parent {
height: 100px;
display: flex;
}
.box1 {
width: 200px;
height: 100px;
background: tomato;
}
.box2 {
height: 100px;
background: red;
flex: 1;
}