<分区>
<分区>
我有一个响应式背景图片,我想在上面垂直居中放置文本。我已经尝试将行高和容器高度设置为相等并且绝对定位 top:50% 但是它不起作用。当我更改窗口大小时,我还希望文本保持居中。据我所知。任何人都可以帮忙。
<!DOCTYPE html>
<html>
<head>
<title>Vertical Center Text</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="Vertically Center Text">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
html, body
{
margin: 0;
padding: 0;
}
.box
{
width: 100%;
height: 700px;
background-color: #1F3AC5;
color: #fff;
float: left;
}
.page-container
{
width: 992px;
margin: 0 auto;
}
.text1
{
float: left;
color: #fff;
background-color: rgba(0, 0, 0, 0.5);
text-transform: uppercase;
font-size: 20px;
padding: 20px;
line-height: 25px;
}
.text2
{
clear: both;
float: left;
color: #fff;
text-shadow: 2px 2px 4px #000000;
font-size: 60px;
line-height: 65px;
}
/*mobile*/
@media only screen and (max-width: 1200px)
{
.box
{
min-height: 475px;
height: calc(100vw / 1.714);
}
}
@media only screen and (max-width: 992px)
{
.box
{
height: 475px;
}
.text1
{
font-size: 16px;
margin: 0 20px;
}
.text2
{
font-size: 40px;
margin: 0 20px;
}
}
</style>
</head>
<body>
<div class="box">
<div class="page-container">
<div class="text1">Hello World</div>
<div class="text2">How are you?</div>
</div>
</div>
</body>
</html>
最佳答案
我已经记录了 CSS 的变化。 Flexbox 用于将 page-container
置于中心。移除所有 float 以保持文档流完整。
关于 flexbox 的更多信息 here .
html,
body {
margin: 0;
padding: 0;
}
.box {
width: 100%;
height: 700px;
background-color: #1F3AC5;
color: #fff;
/* float: left; REMOVED */
display: flex; /* Added */
align-items: center; /* Center vertically */
}
.page-container {
width: 992px;
margin: 0 auto;
}
.text1 {
/* float: left; REMOVED */
color: #fff;
background-color: rgba(0, 0, 0, 0.5);
text-transform: uppercase;
font-size: 20px;
padding: 20px;
line-height: 25px;
}
.text2 {
/* clear: both;
float: left; REMOVED */
color: #fff;
text-shadow: 2px 2px 4px #000000;
font-size: 60px;
line-height: 65px;
}
/*mobile*/
@media only screen and (max-width: 1200px) {
.box {
min-height: 475px;
height: calc(100vw / 1.714);
}
}
@media only screen and (max-width: 992px) {
.box {
height: 475px;
}
.text1 {
font-size: 16px;
margin: 0 20px;
}
.text2 {
font-size: 40px;
margin: 0 20px;
}
}
<div class="box">
<div class="page-container">
<div class="text1">Hello World</div>
<div class="text2">How are you?</div>
</div>
</div>
关于css - 在背景 Div 上垂直居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52214738/