是否有一种 CSS 方法可以使父 div 的宽度与其中所有 div 的宽度相同。像这样:
+--------------------------------------------------+
| DIV |
| |
| +---------+ +---------+ +---------------+ |
| | | | | | | |
| | | | | | | |
| | DIV | | DIV | | DIV | |
| | | | | | | |
| | | | | | | |
| +---------+ +---------+ +---------------+ |
| |
| |
| |
| |
+--------------------------------------------------+
+---------------------------------------+
| DIV |
| +-----------+ +---------------+ |
| | | | | |
| | | | | |
| | | | | |
| | DIV | | DIV | |
| | | | | |
| | | | | |
| | | | | |
| | | | | |
| +-----------+ +---------------+ |
| |
+---------------------------------------+
最后我想让父 div 水平居中。因此,我必须将子 div 的总宽度作为父 div 的宽度。我将使用 display:table 和 margin:0 auto 将父 div 居中。
有什么想法吗?
谢谢!
最佳答案
运行下面的代码片段,看看我已经根据您提供的图片创建了一个类似的布局,
使用完全响应式的 flexbox,一切都居中,一切都可以调整。
父 div 也水平居中。
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100vw;
height: 100vh;
}
.container {
display: flex;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: space-around;
}
.parent_one,
.parent_two {
display: flex;
background-color: blue;
height: 40%;
justify-content: space-around;
align-items: center;
}
.parent_one {
width: 60%;
}
.parent_two {
width: 30%;
}
.child {
background-color: yellow;
width: 30%;
height: 90%;
}
<div class="container">
<div class="parent_one">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
<div class="parent_two">
<div class="child"></div>
<div class="child"></div>
</div>
</div>
关于html - div 与其内部的 div 一样宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35503216/