CSS居中的几种常用方法
作者:互联网
1. text-align: center;
1 <div class="center1"> 2 <span>111</span> 3 </div> 4 5 .center1 { 6 text-align: center; 7 }
2. margin: 0 auto;
(需要先制定一个宽度,让块级元素居中,然后让文字居中.)
1 <div class="center2"> 2 <span>222</span> 3 </div> 4 5 .center2 { 6 width: 100%; 7 margin: 0 auto; 8 text-align: center; 9 }
3. table-cell 实现几个块级元素一起居中展示.
1 <div> 2 <div class="center3">3111</div> 3 <div class="center3">3222</div> 4 <div class="center3">3333</div> 5 </div> 6 7 .center3 { 8 display: table-cell; 9 vertical-align: middle; 10 text-align: center; 11 width: 200px; 12 height: 200px; 13 border: 1px solid red; 14 }
4. 通过line-height和height,设置元素水平垂直居中.
1 <div class="center4"> 2 444 3 </div> 4 5 .center4 { 6 height: 40px; 7 line-height: 40px; 8 text-align: center; 9 background-color: pink; 10 }
5. 使用CSS3 translate
transform: translate(-50%, -50%);
6. 使用CSS3 calc
left: calc(50% - 150px);
7. 使用flex布局 (最好用)
1 <div class="center5"> 2 555 3 </div> 4 5 .center5 { 6 display: flex; 7 height: 40px; 8 align-items: center; // 水平居中 9 justify-content: center; // 垂直居中 10 background-color: skyblue; 11 }
标签:居中,40px,center,text,align,height,几种,CSS 来源: https://www.cnblogs.com/james2306/p/15562347.html