CSS3/CSS之居中解析(水平+垂直居中、水平居中,垂直居中)

CSS3/CSS之居中解析(水平+垂直居中、水平居中,垂直居中)

今天,博主带来的是CSS3/CSS中的居中解析,相信小伙伴们有时候也会被各种居中搞的一脸懵逼把!

居中总体来说可以分为水平居中还有垂直居中,正中央,顾名思义,定义这里就不解释了!

首先,我们来看下垂直居中:

(1)、如果是单行文本,则可以设置的line-height的数值,让其等于父级元素的高度!

<!DOCTYPE html >
< html lang= "en" >
< head >
< meta charset= "UTF-8" >
< meta name= "viewport" content= "width=device-width, initial-scale=1.0" >
< meta http-equiv= "X-UA-Compatible" content= "ie=edge" >
< title >Document </ title >
< style >
.box{
background: green;
height: 200px;
}
a { height: 100%;
line-height: 200px;
color: red;
}
< / style >
</ head >
< body >
< div class= "box" >
< a href= "" >ggg </ a >
</ div >
</ body >
</ html >

(2)、如果元素是行内块级元素,一般会使用diaplay:inline-block,vertical-align:middle,还有一个伪元素让元素内容处于容器中央!给父元素添加伪元素!

<!DOCTYPE html >
< html lang= "en" >
< head >
< meta charset= "UTF-8" >
< meta name= "viewport" content= "width=device-width, initial-scale=1.0" >
< meta http-equiv= "X-UA-Compatible" content= "ie=edge" >
< title >Document </ title >
< style >
.box {
background: green;
height: 200px;
}
.box::after, .box2{
display: inline-block;
vertical-align: middle;
}
.box::after{
content: '';
height: 100%;
}
.box2{ background-color: red; width: 20px; height: 20px;}
< / style >
</ head >
< body >
< div class= "box" >
< div class= "box2" ></ div >
</ div >
</ body >
</ html >

(3)、通过display:flex来实现垂直居中;

父级:display:flex;

子元素:align-self:center;

<!DOCTYPE html >
< html lang= "en" >
< head >
< meta charset= "UTF-8" >
< meta name= "viewport" content= "width=device-width, initial-scale=1.0" >
< meta http-equiv= "X-UA-Compatible" content= "ie=edge" >
< title >Document </ title >
< style >
.box {
background: green;
height: 300px;
width: 600px;
display: flex;
}
.box2{ background: red;
width: 30%;
height: 30%;
align-self: center;

}
< / style >
</ head >
< body >
< div class= "box" >
< div class= "box2" ></ div >
</ div >
</ body >
</ html >

(4)、使用display:table进行垂直居中!

给父元素设置display:table;子元素设置为display:table-cell;

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值