将较少的内联元素强制转换为第一行

问题描述 投票:1回答:3

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

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

通过这些样式,我设法将小div放置在容器的中心。其中4个可以放在一条线上,如果还有更多则放在下一行。当最后一行中少于4个div时,它们的左侧和右侧出现空格。

是否有可能将这些空白空间(总是)强制进入第一行? (保留第1行中最小数量的元素而不是最后一行。)

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

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

What I want:
|            _____   _____            |
|           |     | |     |           |
|           |  1  | |  2  |           |
|           |_____| |_____|           |
|    _____   _____   _____   _____    |
|   |     | |     | |     | |     |   |
|   |  3  | |  4  | |  5  | |  6  |   |
|   |_____| |_____| |_____| |_____|   |
html css css3 positioning
3个回答
3
投票

我想充其量你可以做一些黑客攻击:

选项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>

请告诉我您对此的反馈,谢谢!


1
投票

您可以使用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>

希望这可以帮助!


0
投票

我修复了你发布的请看我的下面的解决方案,也支持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/

© www.soinside.com 2019 - 2024. All rights reserved.