css几种居中的方法

1、内容居中

style="text-align:center"
align="center"

2、元素居中(只适合块级元素)
先设置宽度,再设置margin、padding

width:200px
margin:0px;
padding:0px;

3、垂直居中(适合单独一行垂直居中)
height和line-height设置成一样即可

line-height:40px;
height:40px;

4、内边距方式居中
借助设置相同的上下内边距,实现垂直居中效果,可以用在多行文本上

<style>
#d {padding: 20px 0;}
div{border:solid 1px black;}
</style>

<div id="d">多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容  </div>

5、table方式(适用于图片居中)
首先通过display:table-cell
再借助于单元格的垂直居中来达到效果

<style>
#d {
display: table-cell;
vertical-align: middle;
height:200px;
}
div{
border:solid 1px lightskyblue;}
</style>

<div id="d">
<img src="">
</div>

6、使用绝对定位和负外边距对块级元素居中(ps:必须提前知道被居中块级元素的尺寸)

<style>
#box { width: 300px;
 height: 300px; 
 position: relative; }
 #child { width: 150px; 
 height: 100px; 
 position: absolute; 
 margin: -50px 0 0 0;
 line-height: 100px; }
</style>

<div id="box"> <div id="child">我要居中的内容</div> </div>

7、使用translate居中(兼容性不是很好)

<style>
#box { width: 300px;
 height: 300px; 
 position: relative; }
 #child { background: #93BC49; 
 position: absolute;
 top: 50%; 
 transform: translate(0, -50%); }
 </style>

<div id="box"> <div id="child">我要居中的内容</div> </div>

8、用计算的方式居中元素

<style>
.box { position: relative; 
height: 300px; 
width: 1000px;
border: 1px solid #ccc; }
.child{ position: absolute; 
top: calc(50% - 50px); 
left: calc(50% - 150px); 
width: 300px; 
height: 100px;
 border: 1px solid #000; }
</style>

<div class="box">   
<div class="child">我是要居中的内容</div> </div>

猜你喜欢

转载自blog.csdn.net/dj_fairy/article/details/78511648
今日推荐