【问题标题】:flexbox put last item at next line [closed]flexbox将最后一项放在下一行[关闭]
【发布时间】:2021-04-22 16:32:41
【问题描述】:

我有一个容器

#test {
  display:flex;
  flex-direction:row;
}

p { 

 margin-left:3px;
}
<div id = "test">

<p> 1 </p>
<p> 1 </p>
<p> 1 </p>

</div>

如何将最后一个元素发送到下一行的开头?

【问题讨论】:

    标签: html css


    【解决方案1】:

    您需要在父 div 上设置 wrap 并使最后一个元素的宽度为 100%

     #test {
          display:flex;
          flex-direction:row;
          flex-wrap: wrap
        }
        
        p { 
         margin-left:3px;
        }
        p:last-child{
          width: 100%;
        }
    

    【讨论】:

      【解决方案2】:

      使用last-childorder

      #test {
        display:flex;
        flex-direction:row;
      }
      
      p { 
      
       margin-left:3px;
      }
      
      p:last-child{
         order: -1;
      }
      

      【讨论】:

        【解决方案3】:

        您可能正在寻找的是使用 wrapping flexbox。

        查看this answer,它描述了一个类似的问题,您可以使用flex css 属性说明一行中的项目对一行的“贡献”多少。

        #test {
          display:flex;
          flex-direction:row;
          flex-wrap: wrap;
          width: fit-content;
        }
        
        p {
          margin: 0 0 0 3px;
          padding: 0px;
          flex: 0 0 calc(50% - 3px); # here the - 3px come from the margin-left being 3px
        }
        <div id = "test">
        
        <p> 1 </p>
        <p> 1 </p>
        <p> 1 </p>
        
        </div>

        【讨论】:

        • @Paulie_D 感谢Paulie 的提示!我将另一个答案“翻译”成这个问题! :)
        【解决方案4】:

        您可以使用网格代替 flexbox。将每一行设置为两列,您就可以解决这个问题。

        #test {
          display: grid;
          grid-template-columns: repeat(2, 10px);
        }
        <div id="test">
          <p> 1 </p>
          <p> 1 </p>
          <p> 1 </p>
        </div>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-20
          • 2011-06-05
          • 1970-01-01
          • 2023-04-07
          • 1970-01-01
          • 2018-12-04
          • 1970-01-01
          • 2018-06-21
          相关资源
          最近更新 更多