⼏种常⽤的CSS居中⽅法,⼏⾏代码很简单我们都知道margin:0 auto;可以让元素⽔平居中,但margin:auto却不能让元素垂直居中。
1. 最简单的⽔平居中⽅法
margin:0 auto;
其实上⾯语法是margin-left和margin-right为auto的结合。从⽽达到⽔平居中效果。
2. ⽂字⽔平、垂直居中最简单⽅法
text-align:center
height:50px;
line-height:50px;
只要设置line-height==height,⽂字就可以垂直居中
3. padding填充
利⽤padding和background-clip配合实现div的⽔平居中:
<div class="parent">
<div class="child"></div>
</div>
.parent{
width:400px;
height:200px;
background-color:blue;
}
.child{
width:200px;
height:100px;
padding:50px 100px;
background-color:yellow;
background-clip:content-box;/*居中的关键*/
}
/*padding的取值决定于parent减去child相应的宽⾼的再取⼀半*/
好看的css代码
4. translate(-50%,-50%)
⽤position和transform:translate(-50%,-50%)实现。
<div class="parent">
<div class="child"></div>
</div>
.parent{
width:400px;
height:200px;
background-color:pink;
}
.child{
position:relative;
width:200px;
height:100px;
left:50%;//关键
top:50%;//关键
transform:translate(-50%,-50%);//关键
background-color:yellow;
}
/*这⾥上⾯三句关键是实现的重点,需要注意的是top、left的50%是相对parent的50%,即⼀开始将child向右移动400*50%=200px,向下移动200*50%=1 00px,此时child的左上⾓位遇parent的中⼼点处;此时再⽤translate(-50%,-50%)就可以将child平移⾄居中了,注意这⾥的-50%是相对child元素的宽⾼,即向左移动200*(-50%)=-100px以达到⽔平居中,垂直居中同理*/
5. margin:auto⽔平居中再和margin-top来调整以达到垂直居中。
6. 使⽤flex居中,仅适⽤弹性盒⼦
<div class="parent">
<div class="child">嘻嘻,哈哈</div> </div>
.parent{
display:flex;/**/
width:400px;
height:200px;
background-color:gray;
align-items:center;/*垂直居中*/
justify-content:center;/*⽔平居中*/ }
.child{
background-color:blue;
}
enter;/*垂直居中*/
justify-content:center;/*⽔平居中*/ }
.child{
background-color:blue;
}