场景:
包含在子元素中的文本在父元素中,水平垂直居中。
- 文本只有一行的情况下:
代码
<html>
<head>
<meta charset="UTF-8">
<title>水平垂直居中原始方法-只有一行文本</title>
<style>
.container {
height: 50px;
line-height: 50px;
background-color: yellow;
text-align: center;
/*vertical-align: middle;*/
}
</style>
</head>
<body>
<div class="container">
<div>this is text</div>
</div>
</body>
</html>
展示:
- 需要指定子元素宽高情况下
代码
<html>
<head>
<meta charset="UTF-8">
<title>水平垂直居中原始方法-多行文本1</title>
<style type="text/css">
.container {
position: relative;
background-color: #a0b3d6;
height: 400px;
width: 400px;
}
.inner-box {
position: absolute;
top: 50%;
left: 50%;
height: 150px;
width: 150px;
margin-left: -75px;
margin-top: -75px;
background-color: yellow;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="container">
<div class="inner-box">
this is textthis is textthis is textthis is textthis is textthis is textthis is textthis is text
</div>
</div>
</body>
</html>
现象:
- 无需指定子元素宽高情况下:
代码:
<html>
<head>
<meta charset="UTF-8">
<title>水平垂直居中原始方法-多行文本2</title>
<style type="text/css">
.container {
position: relative;
background-color: #a0b3d6;
height: 400px;
width: 400px;
}
.inner-box {
position: absolute;
height: 150px;
width: 150px;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background-color: yellow;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="container">
<div class="inner-box">
this is textthis is textthis is textthis is textthis is textthis is textthis is text this is text
</div>
</div>
</body>
</html>
现象: 同上
- 使用自适应flex布局方法
代码:
<html>
<head>
<meta charset="UTF-8">
<title>水平垂直居中原始方法-flex方法</title>
<style type="text/css">
.dad{
border: 1px solid red;
display: flex;
height: 100vh;
width: 100vw;
justify-content: center;
align-items: center;
}
</style>
</head>
<body class="dad">
<span>this is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is texthis is text</span>
</body>
</html>
现象:
总结:
其实,父元素完全可以指定body标签,这样相当于指定div的宽为100vw,高为100vh