In a column of flex items, place the last two items in a single row

时光毁灭记忆、已成空白 提交于 2020-01-01 19:04:12

问题


Without modifying the HTML or using some position: absolute hackery, is it possible to make items 6 and 7 in this list appear side-by-side on row 6?

ul {
  border: 1px solid gray;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  list-style-type: none;
}
li {
  width: 33%;
  border: 1px solid #ccc;
  text-align: center;
}
<div class="flex-container">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
  </ul>
</div>

https://jsfiddle.net/511qb3py/


回答1:


Here's one method:

  • Switch the flex-direction to row.
  • Enable wrap.
  • Give each flex item enough width so that only one can fit on a line. This forces the following items to create new lines.
  • Give the last two items (6 and 7) a width that enables both to fit on one line.

ul {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  list-style-type: none;
  border: 1px solid gray;
}
li {
  flex: 0 0 66%; /* flex-grow flex-shrink flex-basis */
  text-align: center;
  border: 1px solid #ccc;
}
li:nth-last-child(-n + 2) {
  flex-basis: 45%;
}
<div class="flex-container">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
  </ul>
</div>



回答2:


You can do it like this:

ul {
  border: 1px solid gray;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  list-style-type: none;
}
li {
  min-width: 33%;
  max-width: 33%;
  border: 1px solid #ccc;
  text-align: center;
  margin-left: 100%;
  margin-right: 100%;
}
li:nth-last-child(-n + 2) {
  margin: 0;
}
<div class="flex-container">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
  </ul>
</div>


来源:https://stackoverflow.com/questions/40011471/in-a-column-of-flex-items-place-the-last-two-items-in-a-single-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!