如何在CSS中集中容器内的多个div

Jan*_*ren 44 html css

我正在测试像Windows地铁一样的中心分频器.如果您检查以下代码:

.container {
    height: 300px;
    width: 70%;
    background: #EEE;
    margin: 10px auto;
    position: relative;
}
.block {
    background: green;
    height: 100px;
    width: 100px;
    float: left;
    margin: 10px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="block">1. name of the company</div>
  <div class="block">2. name of the company</div>
  <div class="block">3. name of the company</div>
  <div class="block">4. name of the company</div>
  <div class="block">5. name of the company</div>
  <div class="block">6. name of the company</div>
  <div class="block">7. name of the company</div>
  <div class="block">8. name of the company</div>
</div>
Run Code Online (Sandbox Code Playgroud)

灰色框是70%并且以屏幕为中心是正确的,但是当我使窗口变宽并且绿色分隔器移动时,您可以看到某些点处的绿色框不是居中的.

我整天都在寻找这个:s

怎么能帮我这个呢?

Geo*_*rge 75

您可以将样式display: flex应用于容器并将justify-content: centers 显示为内联块元素:

.container {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    width: 70%;
    background: #eee;
    margin: 10px auto;
    position: relative;
    text-align:center;
}

.block {
    background: green;
    height: 100px;
    width: 100px;
    margin: 10px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
    <div class="block">1. name of the company</div>
    <div class="block">2. name of the company</div>
    <div class="block">3. name of the company</div>
    <div class="block">4. name of the company</div>
    <div class="block">5. name of the company</div>
    <div class="block">6. name of the company</div>
    <div class="block">7. name of the company</div>
    <div class="block">8. name of the company</div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是一个更新的小提琴

请注意,我已经注释掉了你们之间的空白区域flex-wrap: wrap.由于元素现在以内联方式显示,因此您的空格将被确认.这是"打空空间" 的众多方法之一.

  • 几乎在那里,我想,如果我让屏幕更小,盒子是完美的中心,但如果我使它3-3-2盒子然后底部行也居中,他们实际上应该在盒子1和列1下对齐 (2认同)

Pet*_*ete 6

如果您更改.block元素的样式而不是float:left;使用display:inline-block;,则可以添加text-align:center.container