css垂直居中几种方式
常用的css垂直居中几种布局方式:
1-利用定位position+margin_auto
2-定位配合css3位移position+transform
3-利用内联块元素 display:inline-block
4-弹性盒模型 flex+justify-content+align-items
5-弹性盒模型 flex+margin_auto
6-网格布局 Grid
html代码:
<div class="content"> <div class="box"></div> </div>
css代码:
利用定位position+margin_auto
.content { width: 500px; height: 300px; border: 1px solid #0a3b98; position: relative; } .box { width: 100px; height: 40px; background: #f0a238; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }
2.定位配合css3位移position+transform
.content { width: 500px; height: 300px; border: 1px solid #0a3b98; position: relative; } .box { width: 100px; height: 40px; background: #f0a238; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
3.利用内联块元素 display:inline-block
.content{ width:500px; height:300px; border:1px solid #0a3b98; text-align: center; } .content:before{ content: ''; height:100%; width:0; display: inline-block; vertical-align: middle; } .box{ width:100px; height:40px; background: #f0a238; display: inline-block; vertical-align: middle; }
4.弹性盒模型 flex+justify-content+align-items
.content { width: 500px; height: 300px; border: 1px solid #0a3b98; display: flex; justify-content: center; align-items: center; } .box { width: 100px; height: 40px; background: #f0a238; }
5.弹性盒模型 flex+margin_auto
.content { width: 500px; height: 300px; border: 1px solid #0a3b98; display: flex; } .box { width: 100px; height: 40px; background: #f0a238; margin: auto; }
6.网格布局 grid+justify-content+align-items
.content { width: 500px; height: 300px; border: 1px solid #0a3b98; display: grid; justify-content: center; align-items: center; } .box { width: 100px; height: 40px; background: #f0a238; }
效果:
本文作者: Jasmine
本文链接: https://www.jianbaizhan.com/article/710
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!