gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:31:49 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com