已知父元素是块级元素(block),现要让子元素在父元素中垂直居中
(1) 父元素设置高度和行高,并且使高度与行高相等(height = line-height);子元素不设置高度和行高
<!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>
<style>
div {
background: grey;
height: 40px;
line-height: 40px;
}
</style>
</head>
<body>
<div>
<span>
Hello World!
</span>
</div>
</body>
</html>
(2) 父元素不设置高度, 设置行高;子元素不设置高度和行高
<!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>
<style>
div {
background: gray;
line-height: 40px;
}
</style>
</head>
<body>
<div>
<span>
Hello World!
</span>
</div>
</body>
</html>
(3) 父元素不设置高度和行高;子元素设置行高,不设置高度和行高
<!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>
<style>
div {
background: gray;
}
span {
line-height: 40px;
}
</style>
</head>
<body>
<div>
<span>
Hello World!
</span>
</div>
</body>
</html>