1、可以用一个自然高度的容器吗?
给容器加上相等的上下内边距让内容居中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div{
/* 关键样式 */
padding: 4em;
/* 基本样式 */
color: #fff;
background-color: #0072b0;
border-radius: .5em;
/* 水平居中 */
text-align: center;
}
</style>
</head>
<body>
<div>这是测试用的文字</div>
</body>
</html>
2、容器需要指定高度或者避免使用内边距吗?
指定高度,对容器使用display: table-cell和vertical-align: middle。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div{
/* 指定宽、高 */
height: 200px;
width: 600px;
/* 关键样式 */
display: table-cell;
vertical-align: middle;
/* 基本样式 */
color: #fff;
background-color: #0072b0;
border-radius: .5em;
/* 水平居中 */
text-align: center;
}
</style>
</head>
<body>
<div>这是测试用的文字</div>
</body>
</html>
3、可以用Flexbox吗?
如果不需要支持IE9,可以用Flexbox居中内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div{
/* 关键样式 */
display: flex;
justify-content: center;
align-items: center;
height: 200px;
/* 基本样式 */
color: #fff;
background-color: #0072b0;
border-radius: .5em;
}
</style>
</head>
<body>
<div>这是测试用的文字</div>
</body>
</html>
4、容器里面的内容只有一行文字吗?
设置一个大的行高,让它等于理想的容器高度。这样会让容器高度扩展到能够容纳行高。如果内容不是行内元素,可以设置为inline-block。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div{
/* 关键样式 */
display: inline-block;
line-height: 10rem;
/* 基本样式 */
width: 500px;
color: #fff;
background-color: #0072b0;
border-radius: .5em;
text-align: center;
}
</style>
</head>
<body>
<div>这是测试用的文字</div>
</body>
</html>
5、容器和内容的高度都知道吗?
将内容绝对定位。(只有当前面提到的方法都无效时才推荐这种方式。)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
/* 容器宽高 */
div{
width: 600px;
height: 300px;
background-color: #0072b0;
}
/* 内容宽高,内容高度为22px,
top: (容器高度-内容高度)/2
left:(容器宽度-内容宽度)/2
*/
p{
width: 200px;
background-color:sandybrown;
/* 关键样式,需要进行计算距离 */
position: absolute;
top: 139px;
left: 200px;
}
</style>
</head>
<body>
<div>
<p>这是测试用的文字</p>
</div>
</body>
</html>
6、不知道内部元素的高度?
用绝对定位结合变形(transform)。(还是只有当前面提到的方法都无效时才推荐该方法。)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
/* 容器宽高 */
div{
width: 600px;
height: 300px;
background-color: #0072b0;
/* 相对定位 */
position: relative;
}
p{
width: 200px;
background-color:sandybrown;
/* 绝对定位 */
/* 关键样式 */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div>
<p>这是测试用的文字</p>
</div>
</body>
</html>