管理 justify-content:最后一行的空格 [英] Managing justify-content: space-between on last row

查看:23
本文介绍了管理 justify-content:最后一行的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是每行有三个 flex 项目并使用 space-between 以便每行中的第一和第三个项目接触容器的外部但保持等距.

这按预期工作,但是当第五个项目没有按照我想要的那样对齐时,第二行会出现问题,直接在第二个项目下方.我将拥有可变数量的内容,因此需要布局来处理任意数量的框.

我在下面展示了我的代码.谁能告诉我如何解决这个问题?

.main{背景:#999;保证金:0 自动;宽度:1300px;显示:弹性;flex-wrap: 包裹;对齐内容:间隔;}.盒子{背景:#7ab9d7;颜色:#555;高度:300px;宽度:30%;底边距:30px;文本对齐:居中;字体大小:30px;填充顶部:120px;}

<div class="box">1</div><div class="box">2</div><div class="box">3</div><div class="box">4</div><div class="box">5</div>

解决方案

使用一个不可见的伪元素,占据容器的最后一个槽位:

.main::after {高度:0;宽度:30%;内容: "";}

高度为 0,这样当行被填充时,伪元素从下一行开始,它不会为容器增加高度.

完整代码:

.main {背景:#999;边距:0 自动;宽度:500px;显示:弹性;flex-wrap: 包裹;对齐内容:间隔;}.盒子 {背景:#7ab9d7;颜色:#555;高度:30px;宽度:30%;底边距:30px;文本对齐:居中;字体大小:30px;填充顶部:120px;}.main::after {高度:0;宽度:30%;内容: "";}

<div class="box">1</div><div class="box">2</div><div class="box">3</div><div class="box">4</div><div class="box">5</div>

I am aiming to have three flex items per row and use space-between so the first and third items in each row touch the outside of the container but remain equally spaced.

This works as intended but the problems arise in the second row when the fifth item doesn't align as I want, directly below the second item. I will have a variable amount of content so need the layout to work with any number of boxes.

I have shown my code below. Can anyone tell me how to fix this?

.main{
    background: #999;
    margin:0 auto;
    width:1300px;
    display:flex;
    flex-wrap: wrap;
    justify-content: space-between;
}


.box{
    background: #7ab9d7;
    color: #555;
    height: 300px;
    width: 30%;
    margin-bottom: 30px;
    text-align: center;
    font-size: 30px;
    padding-top: 120px;
}

<div class="main">
         
          <div class="box">1</div>
          <div class="box">2</div>
          <div class="box">3</div>
          <div class="box">4</div>
          <div class="box">5</div>
         
</div>

解决方案

Use an invisible pseudo-element that occupies the last slot in the container:

.main::after {
  height: 0;
  width: 30%;
  content: "";
}

The height is 0 so that when rows are filled, and the pseudo-element starts the next line, it doesn't add height to the container.

Full code:

.main {
  background: #999;
  margin: 0 auto;
  width: 500px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.box {
  background: #7ab9d7;
  color: #555;
  height: 30px;
  width: 30%;
  margin-bottom: 30px;
  text-align: center;
  font-size: 30px;
  padding-top: 120px;
}
.main::after {
  height: 0;
  width: 30%;
  content: "";
}

<div class="main">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
  <div class="box">5</div>
</div>

这篇关于管理 justify-content:最后一行的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆