解决 flex 布局中 space-between 最后一行元素的排列问题

1,783 阅读1分钟

问题:假如我们有8个元素

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>
<style>
  ul {
    width: 300px;
    height: 400px;
    background: #f0f0f0;
    list-style: none;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 5px;
  }
  ul li {
    width: 90px;
    height: 50px;
    text-align: center;
    line-height: 50px;
    background: pink;
    border-radius: 10px;
  }
 </style>

由于 space-between 就是两端布局,当最后一行不满三个的时候,最后一排会分在两端。

解决方案:使用 after 伪元素来解决该问题

ul:after{
  content: '';
  width: 90px;
}