-
已知元素高度
方式一:
<html>
<head>
<style>
.box {
width: 200px;
height: 200px;
position: relative;
}
.content {
width: 40px;
height: 40px;
background: lightgray;
position: relative;
margin: 0 auto;
top: 50%;
margin-top: -20px;
}
</style>
</head>
<body>
<div class="box">
<div class="content"></div>
</div>
</body>
</html>
方式二:
<html>
<head>
<style>
.box {
width: 200px;
height: 200px;
position: relative;
}
.content {
width: 40px;
height: 40px;
background: lightgray;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<div class="box">
<div class="content"></div>
</div>
</body>
</html>
-
未知元素高度
<html>
<head>
<style>
.box {
width: 200px;
height: 200px;
position: relative;
}
.content {
background: lightgray;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="box">
<div class="content">居中</div>
</div>
</body>
</html>
-
flex布局
<html>
<head>
<style>
.box {
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
}
.content {
background: lightgray;
}
</style>
</head>
<body>
<div class="box">
<div class="content"></div>
</div>
</body>
</html>
-
before伪元素+vertical-align: middle;
<html>
<head>
<style>
.box {
width: 200px;
height: 200px;
text-align: center;
font-size: 0;
border: 1px dotted #f00;
}
.box:before {
content: "";
height: 100%;
width: 0;
vertical-align: middle;
}
.content {
background: lightgray;
font-size: 14px;
display: inline-block;
}
</style>
</head>
<body>
<div class="box">
<div class="content">居中</div>
</div>
</body>
</html>