<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>行高等于高只能让单行文本垂直居中</title></title>
<style>
/* 优化前 */
.box {
width: 150px;
height: 50px;
line-height: 50px;
text-align: center;
margin-bottom: 100px;
border: 1px solid red;
}
/* 优化后 */
/* 多行文本垂直对齐的几种方法 */
/* 方法1.父元素设置display: table; 子元素设置display: table-cell; vertical-align: middle; */
/* .box {
display: table;
width: 150px;
height: 50px;
line-height: 50px;
text-align: center;
margin-bottom: 100px;
border: 1px solid red;
}
.box span {
display: table-cell;
vertical-align: middle;
} */
/* 方法2.父元素设置line-height: 50px; 子元素设置display: inline-block;
vertical-align: middle;
line-height: 18px; */
/* .box {
width: 150px;
height: 50px;
line-height: 50px;
text-align: center;
margin-bottom: 100px;
border: 1px solid red;
}
.box span {
display: inline-block;
vertical-align: middle;
line-height: 18px;
} */
/* 方法3.父元素设置高度line-height: 150px; 子元素设置display: inline-block;
position: relative;
top:50%;
transform: translateY(-50%)*/
.box {
width: 150px;
height: 150px;
text-align: center;
margin-bottom: 100px;
border: 1px solid red;
}
.box span {
display: inline-block;
position: relative;
top:50%;
transform: translateY(-50%);
}
/* 方法4.父元素弹性布局 定义flex 子项的对齐方式align-items: center*/
/* .box {
display: flex;
width: 150px;
height: 150px;
text-align: center;
margin-bottom: 100px;
border: 1px solid red;
} */
.imgbox {
width: 300px;
height: 200px;
line-height: 200px;
}
.imgbox img {
/* 设置元素与文本 垂直对齐 */
vertical-align: middle;
}
</style>
</head>
<body>
<div class='box'>
<span>猥琐发育,别浪<br>
稳住我们能赢</span>
</div>
<div class="imgbox">
<img src="./1.png" alt="">
用户名
</div>
</body>
</html>
效果图:
优化前
优化后: