<!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>
<link rel="stylesheet" href="./style.css" />
<style >
#box{
width: 300px;
height: 300px;
background-color: #f00;
}
#content{
width: 50px;
height: 50px;
background-color: orange;
}
</style>
</head>
<body>
<div id="box">
<div id="content"></div>
</div>
</body>
</html>
子元素相对父元素垂直居中的8大方法,CSS面试题常考,上面是基本代码样式,下面是方法整理如下,话不多说,肝着!
第一种方法: flex css3的flex
#content{
display: flex;
justify-content: center;
align-items: center;
}
第二种方法 flex(父)+margin(子)
#box{
display:flex;
}
#content{
margin:auto;
}
第三种方法:定位方法 position + calc
#box{
position: relative;
}
#content{
position: absolute;
left: calc(50% - 25px);
top: calc(50% - 25px);
}
第四种方法:position + margin.
#box{
position: relative;
border: 1px solid red;/*防止垂直方向margin重叠*/
}
#content{
margin-left: calc(50% - 25px);
margin-top: calc(50% - 25px);
}
第五种方法 :position + margin(2)
#box {
position: relative;
}
#content{
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px;
margin-left: -25px;
}
第六种方法: position + margin(3)
#box{
position: relative;
}
#content{
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
margin: auto;
}
第七种 方法:position + transform
#box{
position: relative;
}
#content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
第八种方法 : lineheight(父) + display:inline-block(子)
#box{
line-height: 325px;
vertical-align: center;
text-align: center;
}
#content{
display: inline-block;
}