html - 在 body 中垂直居中两个 div

标签 html css

这是一个更复杂问题的简化版本。假设 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/

相关文章:

php - 根据登录用户查看休假详细信息

javascript - reCAPTCHA 未正确显示?

html - 获得一致的页脚间距

javascript - 在触摸设备上通过拖放启用滚动

image - CSS 3 不透明度过渡不适用于 <img>

html - 显示在另一个 div 后面的子菜单

html - X-UA-Compatible 在包含在条件注释中时不起作用?

javascript - 为什么 Phaser 游戏在移动设备上滞后

css - 如何在CSS中获取当前文本大小

javascript - 可以从 KnockoutJS 模型和 View 中删除事件处理吗?