首页 > 解决方案 > 行内块 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 与上面的不对齐。

https://imgur.com/a/GLgFSsV

标签: htmlcss

解决方案


也是因为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>


推荐阅读