将较少的内联元素强制到第一行

Forcing the less inline-elements to the first line

随机数 div 通过 javascript 放置在我的容器中 div。

<div id="container"></div>
#container { text-align: center; width: 480px; }
#container div { display: inline-block; width: 100px; }

通过这些样式,我设法将小 div 放置在容器的中心。 其中4个可以排成一行,如果多了剩下的放在下一行。 当最后一行少于4个div时,出现左右两边的space。

是否可以将这些空的spaces(总是)强制到第一行? (在第一行而不是最后一行保留最少数量的元素。)

会喜欢纯粹的 CSS 解决方案(但如果不存在,当然其他任何东西都可以)。谢谢!

What I have:
|    _____   _____   _____   _____    |
|   |     | |     | |     | |     |   |
|   |  1  | |  2  | |  3  | |  4  |   |
|   |_____| |_____| |_____| |_____|   |
|            _____   _____            |
|           |     | |     |           |
|           |  5  | |  6  |           |
|           |_____| |_____|           |

What I want:
|            _____   _____            |
|           |     | |     |           |
|           |  1  | |  2  |           |
|           |_____| |_____|           |
|    _____   _____   _____   _____    |
|   |     | |     | |     | |     |   |
|   |  3  | |  4  | |  5  | |  6  |   |
|   |_____| |_____| |_____| |_____|   |

我认为你最多可以做一些技巧:

选项 1:

使用flexboxwrap-reverse它:

#container {
  text-align: center;
  width: 480px;
  display:flex;
  flex-wrap:wrap-reverse;
  justify-content:center;
}
#container div {
  width: 100px;
  height: 100px;
  border:1px solid red;
  margin:5px;
}
<div id="container">
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>1</div>
  <div>2</div>
</div>

选项 2:

您可以做的另一件事是使用 transform 缩放:

#container {
  text-align: center;
  width: 480px;
  transform: scaleY(-1);
}
#container div {
  width: 100px;
  height: 100px;
  border:1px solid red;
  margin:5px;
  display:inline-block;
  transform: scaleY(-1);
}
<div id="container">
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>1</div>
  <div>2</div>
</div>

让我知道您对此的反馈,谢谢!

您可以使用 CSS Flexbox。您可以巧妙地使用 flex-wrap: wrap-reverse;,它将完成工作。

看看下面的代码:

body {
  margin: 10px;
}

.box-holder {
  width: 280px;
  display: flex;
  flex-wrap: wrap-reverse;
  justify-content: center;
}

.box {
  width: 50px;
  height: 50px;
  margin: 5px;
  background: #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="outer">
  <div class="box-holder">
    <div class="box one">1</div>
    <div class="box two">2</div>
    <div class="box three">3</div>
    <div class="box four">4</div>
    <div class="box five">5</div>
    <div class="box six">6</div>
  </div>
</div>

希望对您有所帮助!

我修复了您发布的问题,请参阅我下面也支持 IE9 的解决方案。我修复了使用子元素。

HTML

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

CSS

.container{text-align:center;width:400px}
.container div{width:100px;height:100px;background:red;display:inline-block;margin-left: -4px;}
.container div:first-child{margin-left:100px;}
.container div:nth-child(2){margin-right:100px;}

https://jsfiddle.net/hardyrajput/Ly8667n3/2/