这是一个更复杂问题的简化版本。假设 body 中有两个 div,它们必须垂直居中。由于一些其他要求,DOM 无法更改。因此,只有通过更改 css,我才需要将它们垂直居中对齐。我已经尝试过许多其他 stackoverflow 帖子,但到目前为止还无法正常工作。
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<style>
body{
}
.div1{
display: block;
background: red;
width: 300px;
}
.div2{
display: block;
background: green;
width: 300px;
}
</style>
</head>
<body>
<div class="div1">
<p>This is div1</p>
</div>
<div class="div2">
<p>This is div2</p>
</div>
</body>
</html>
最佳答案
这可以使用 flexbox .
html,
body {
height: 100%;
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
查看此 CodePen
关于html - 在 body 中垂直居中两个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31976781/