内部块级元素的高度要小于容器(父元素)
方案一:行高 = 容器高度(单行内联元素)
限制条件:仅用于单行内联元素 display:inline 和 display: inline-block;
给容器添加样式
height: 100px;
line-height: 100px;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.box {
border: 1px solid gray;
height: 100px;
line-height: 100px;
}
</style>
</head>
<body>
<div class="box">
<span class="item">垂直居中 -- 内联元素 display:inline</span>
</div>
</body>
</html>
方案二:flex布局【推荐】
给容器添加样式
display: flex;
align-items: center;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.box {
width: 100px;
height: 100px;
border: 1px solid gray;
display: flex;
align-items: center;
}
.item {
width: 50px;
height: 50px;
border: 1px solid red;
background: yellow;
}
</style>
</head>
<body>
<div class="box">
<span class="item"></span>
</div>
</body>
</html>
方案三:子绝父相 + transform(CSS3)
限制条件:浏览器需支持CSS3,比较老的浏览器不适用
给容器(父元素)添加样式
position: relative
给内部元素添加样式
position: absolute;
top: 50%;
transform: translate(0, -50%);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.box {
width: 100px;
height: 100px;
border: 1px solid gray;
position: relative;
}
.item {
width: 50px;
height: 50px;
border: 1px solid red;
background: yellow;
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
</style>
</head>
<body>
<div class="box">
<span class="item"></span>
</div>
</body>
</html>
方案四:子绝父相 + 自动外边距(指定高度)
限制条件:内部元素需限定高度
给容器(父元素)添加样式
position: relative
给内部元素添加样式
position: absolute;
top: 0;
bottom: 0;
margin: auto;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.box {
width: 100px;
border: 1px solid gray;
height: 100px;
position: relative;
}
.item {
position: absolute;
top: 0;
bottom: 0;
margin: auto;
background-color: yellow;
height: 20px;
}
</style>
</head>
<body>
<div class="box">
<span class="item">1111</span>
</div>
</body>
</html>