首页 文章

CSS Flexbox:具有左对齐元素的中心容器[重复]

提问于
浏览
0

这个问题在这里已有答案:

我在这里设置了一个简短的演示:codepen.io . 我有一个带有多个盒子的弹箱 . 我喜欢左对齐的最后一个元素,而不是漂浮在中间 . 我可以用任何方式左对齐元素并简单地将容器放在中心位置?

容器的CSS代码在这里,其中一个框的宽度/高度为100px:

.container {
  padding: 1em;
  display: flex;
  flex-wrap: wrap;
  min-width: calc(300px + 6em);
  max-width: calc(400px + 8em);
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  background: red;
}

谢谢!

编辑:我正在寻找的解决方案并不像让最后一个项目与网格对齐那么简单;更具体地说,我希望屏幕宽度是动态的,因此容器元素始终水平居中并与其容器齐平 .

2 回答

  • 0

    在最后一个项目上使用 margin-right: auto; (使用 :last-child )添加一个边距,将您的框向左推:

    .container {
      padding: 1em;
      display: flex;
      overflow: auto;
      flex-wrap: wrap;
      min-width: calc(300px + 6em);
      max-width: calc(400px + 8em);
      align-items: center;
      justify-content: center;
      background: red;
    }
    .box {
      width: 100px;
      height: 100px;
      background: #000;
      margin: 1em;
      display: block;
    }
    
    .box:last-child { margin-right: auto; }
    
    <h1> try resizing window</h1>
    <div class="container">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>
    
  • 0

    我使用Chrome的“Inspect”功能将justify-content更改为“flex-start” .

    这似乎产生了你想要的结果 .

    enter image description here

相关问题