html - 如何在考虑周围空间的情况下将弹性盒的最后一个元素向右对齐?

标签 html flexbox

我有一个包含 7 个元素的 flex-div。

<div class="d-flex flex-wrap justify-content-around">
    <div style="width: 350px">
        [...]
    </div>
    [6 more identical divs]
</div>

在大屏幕上,每行有 3 个 div,在中型屏幕上有 2 个,在小屏幕上只有 1 个。最后一个元素始终居中,但我希望它向右对齐。我在最后一个元素上尝试了 margin-left: auto 但由于 justify-content-around 右侧应该有空间(大屏幕上的前 2 行,前 3 行)中等屏幕上的行)。不幸的是,margin-left: auto 将最后一个元素一直推到右侧,而没有来自 justify-content-around 的空间。如何定位最后一个元素,就像它是右列的元素一样?

.d-flex {
  display: flex
}

.flex-wrap {
  flex-wrap: wrap
}

.justify-content-around {
  justify-content: space-around
}

.card {
  border: 1px solid rgba(0, 0, 0, .125)
}

.ml-auto {
  margin-left: auto
}
<h3>
  Without margin-left: auto
</h3>
<div class="d-flex flex-wrap justify-content-around">
  <div class="card" style="width: 200px">
    1
  </div>
  <div class="card" style="width: 200px">
    2
  </div>
  <div class="card" style="width: 200px">
    3
  </div>
  <div class="card" style="width: 200px">
    4
  </div>
  <div class="card" style="width: 200px">
    5
  </div>
  <div class="card" style="width: 200px">
    6
  </div>
  <div class="card" style="width: 200px">
    7 is centered
  </div>
</div>
<h3>
  With margin-left: auto
</h3>
<div class="d-flex flex-wrap justify-content-around">
  <div class="card" style="width: 200px">
    1
  </div>
  <div class="card" style="width: 200px">
    2
  </div>
  <div class="card" style="width: 200px">
    3
  </div>
  <div class="card" style="width: 200px">
    4
  </div>
  <div class="card" style="width: 200px">
    5
  </div>
  <div class="card" style="width: 200px">
    6
  </div>
  <div class="card ml-auto" style="width: 200px">
    7 is too far to the right
  </div>
</div>

最佳答案

它来自

1 2
3 4
5 6
7 8

让 7 低于 6 是很棘手的,但我们可以说这不是你的意思,只是想将 7 对齐到左侧。

让我们开始删除所有这些 style=width,如果您想编辑 div 的宽度,您需要编辑每个 div,将其转储到 CSS 中会更有效。

<div class="card">
 4
</div>

这是调整后的CSS

.flex-wrap {
  flex-wrap: wrap;
}

.justify-content-around {
  justify-content: space-between;
  display: flex;
}

.card {
  border: 1px solid rgba(0, 0, 0, 0.125);
  width: 200px;
}

如果你想让它右对齐,那么你可以使用JS,但它很困难,因为你使用 justify 可能会发生冲突。

关于html - 如何在考虑周围空间的情况下将弹性盒的最后一个元素向右对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72084419/

相关文章:

php - 当网站托管在远程服务器 wordpress 中时,导航无法正确呈现

jquery - 单击 Bootstrap 中的按钮后如何去除光环?

javascript - 如何使我的函数在值更改时而不是单击按钮时运行?

html - Flexbox:在屏幕中间居中元素

javascript - 防止外部源使用 Javascript 修改我的 HTML

html - 为任何浏览器(跨浏览器)在中心和左右定位 div

html - 为什么当我使用 flex-direction 时我的 div 消失了?

html - 当 child 伸出 window 时,我的 flexbox 下方出现大空间

html - Flexbox 高度约束 100% 的可用空间