一。垂直居中
1.单行文本实现居中:设置行高
.box {
width:200px;
height:200px;
line-height:200px;//实现单行文本居中
background:red;
}
.text {
vertical-align: middle;
}
这种主要给父元素固定高度,利用line-height属性来使文字实现垂直居中。只能在单行文本下使用。
2.利用display:table-cell不推荐使用
/*第一种:display:table-cell*/
.box{
background: red;
width: 150px;
height: 150px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.div1{
/*width: 50px;*/
height: 20px;
background: green;
}
.div2{
background: yellow;
}
</style>
<body>
<div class="box">
<div class="div1">可大可看看</div>
<div class="div2">我不知道</div>
<div class="div3">哦哦</div>
利用了表格样式的居中方式。可以实现盒子和文字居中。
3.display:flex;
/*第一种:display:flex;*/
.box{
background: red;
width: 150px;
height: 150px;
display: flex;
align-items: center; /*定义元素垂直居中*/
justify-content: center; /*定义容器里的元素水平居中*/
}
.div1{
/*width: 50px;*/
/*height: 20px;*/
background: green;
}
.div2{
background: yellow;
}
通过弹性魔盒来实现居中,这种方式特别优雅只需要给父元素添加就可以,不论你子元素是什么样子都居中
4.定位position(推荐)万能
/*第4种:position;*/
.box{
background: red;
width: 150px;
height: 150px;
position: relative;
}
.div1{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: green;
}