首页 > 解决方案 > CSS:如何将最后一个元素向左对齐

问题描述

由于 justify-content: space-around 规则,当第 4 个块向下跳时,它变成了中间

我能否以某种方式仍然使用空格规则,但让最后一个块不跳到中心,而是跳到左边,就像在屏幕截图中一样?PS我仍然需要 justify-content: space-around 因为它响应边距

这是代码https://jsfiddle.net/s4fbtkyg/

<html>
<body>

<style>
  .block{
  background-color: grey;
  flex-basis: 100px;
  margin-bottom: 5px;
}

.container{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
</style>

<div class="container">
  <div class="block">1</div>
  <div class="block">2</div>
  <div class="block">3</div>
  <div class="block">4</div>
 </div>
</body>
</html>

截屏

标签: htmlcssflexbox

解决方案


您可能需要考虑使用 CSS 网格来完成此任务:

grid-template-columns: repeat(auto-fit, 100px); //100px being the width of your choosing

这是代码:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
<div class="container">
  <div class="block">1</div>
  <div class="block">2</div>
  <div class="block">3</div>
  <div class="block">4</div>
 </div>
</body>
</html>

CSS

.block{
  background-color: grey;
}

.container{
  display: grid;
  grid-gap: 5px;
  grid-template-columns: repeat(auto-fit, 100px);
  justify-content: space-around; //you can still use justify-content: space-around

}

小提琴:小提琴链接


推荐阅读