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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值