一。垂直居中
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;
}