老生长谈的问题了,之前都是看别人的,今天抽空自己总结一下,方便自己复习。
1.flex
html:
<div class="wrap">
<section class="son"></section>
</div>
css:
.wrap {
display:flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background-color: #ccc;
}
.son {
width: 100px;
height: 30px;
background-color: #d60;
}
效果:
复制代码
2.absolute+transform
html:
<div class="wrap">
<div class="son"></div>
</div>
css:
.wrap {
width: 200px;
height: 200px;
background-color: #ccc;
position: relative;
}
.son {
width: 100px;
height: 30px;
background-color: #a45;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
效果:
复制代码
3.absolute+margin
html:
<div class="wrap">
<div class="son"></div>
</div>
css:
.wrap {
width: 200px;
height: 200px;
background-color: #ccc;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: #e45;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
效果:
复制代码
总结一下,为什么优先使用transform,因为margin-left/margin-top涉及回流和重绘,
left/top/margin 之类的属性会影响到元素在文档中的布局,当对布局(layout)进行动画时,该元素的布局改变可能会影响到其他元素在文档中的位置,就导致了所有被影响到的元素都要进行重新布局,浏览器需要为整个层进行重绘并重新上传到 GPU,造成了极大的性能开销。
transform 属于合成属性(composite property),对合成属性进行 transition/animation 动画将会创建一个合成层(composite layer),这使得被动画元素在一个独立的层中进行动画。通常情况下,浏览器会将一个层的内容先绘制进一个位图中,然后再作为纹理(texture)上传到 GPU,只要该层的内容不发生改变,就没必要进行重绘(repaint),浏览器会通过重新复合(recomposite)来形成一个新的帧。
转载于:https://juejin.im/post/5cbd76c1f265da039b086d74