html - 行内块 div 的水平对齐
问题描述
我显示了一系列 div 内联块(并且左右边距为 5%),如您所知,一旦达到第一行 div 的限制,其余 div 会自动转到第二行和依此类推(你知道,而不是溢出父级)。然而,这种行为有一个小细节,第二行的元素与第一行的元素没有水平对齐。我知道这是由于边距引起的,但我仍然不知道如何使所有元素等距。以下代码表示该部分的体系结构。
.parent_div {
width: 75%;
float: right;
/* The "parent of the parent" has its clearfix class*/
}
.child_div {
margin-left: 5%;
margin-right: 5%;
display: inline-block;
}
h4 {
display: inline-block;
}
p {
display: inline-block;
}
}
<div class="parent_div">
<div class="child_div">
<h4>Some text: </h4>
<p>some info.</p>
</div>
<div class="child_div">
<h4>Some text: </h4>
<p>some info.</p>
</div>
<div class="child_div">
<h4>Some text: </h4>
<p>some info.</p>
</div>
<div class="child_div">
<h4>Some text: </h4>
<p>some info.</p>
</div>
<div class="child_div">
<h4>Some text: </h4>
<p>some info.</p>
</div>
</div>
您可以在这里再次看到 div 的结构,并且您还可以观察到下面的 div 与上面的不对齐。
解决方案
也是因为margin,但主要是因为每个div中内容的长度不同。我能想到的实现你想要的最好方法是使用网格。
.parent_div {
width: 75%;
float: right;
display: grid;
grid-gap: 2%;
grid-template-columns: repeat(auto-fill, minmax(300px, max-content));
}
.parent_div .child_div h4 {
display: inline-block;
}
.parent_div .child_div p {
display: inline-block;
}
<div class="parent_div">
<div class="child_div">
<h4>Some text111: </h4> <p>some info 3234r32.</p>
</div>
<div class="child_div">
<h4>Some text22: </h4> <p>some info 34.</p>
</div>
<div class="child_div">
<h4>Some text 232434: </h4> <p>some infods 33.asr23</p>
</div>
<div class="child_div">
<h4>Some text 3243: </h4> <p>some infodsf s34.</p>
</div>
<div class="child_div">
<h4>Some text33: </h4> <p>some infodfc fdsf342.</p>
</div>
<div class="child_div">
<h4>Some text22: </h4> <p>some info 34.</p>
</div>
<div class="child_div">
<h4>Some text 3243 234234: </h4> <p>some infodsf s34.sd</p>
</div>
<div class="child_div">
<h4>Some text33: </h4> <p>some infodfc fdsf342.</p>
</div>
<div class="child_div">
<h4>Some text22: </h4> <p>some info 34.</p>
</div>
</div>
推荐阅读
- angular - 已解决 - ActivatedRoute 角度单元测试
- python - discord py“未知角色”
- javascript - 这个特定的嵌套 for 循环如何在原生 JavaScript 中工作?
- python - 熊猫选择相应 nan 值的前一列值
- python - jinja2.exceptions.TemplateNotFound 错误的问题
- c++ - 编译器差异:在 const 成员函数中定义的可变 lambda 中捕获值时的“this”类型
- bash - 使用变量设置 Docker GitLab root 密码?
- java - equalsIgnoreCase 在自身上被调用。错误
- reactjs - Material-UI:`css` 功能已弃用。改用 `styleFunctionSx`
- python - 用于裁剪的 GUI 测量图片大小