首页 > 解决方案 > 在具有可塑性列数的列中居中

问题描述

我试图列出一系列相同大小的元素。我希望这些元素在左右两侧以均匀的间距显示(垂直居中?),并且彼此之间的间距均匀。最大的问题是列表需要能够适应屏幕大小的变化和元素数量的变化。因此,每行的宽度和元素需要根据需要进行更新。底行也应该理想地与上面的对齐。

这是迄今为止我能得到的最接近的。

HTML

<div class="outer">
  <div class="inner">
  </div>
</div>
... repeated as any times as there are blocks.
<div class="outer">
  <div class="inner">
  </div>
</div>

CSS

body {
  text-align: justify;
  margin:0;
  width: auto; 
}

.outer {
  background:blue;
  width: 100px;
  height: 90px;
  display: inline-block;
  text-align: center;
}

.inner {
  background:red;
  width: 90px; 
  height: 90px;
  display: inline-block;
  text-align: center;
}

JSFiddle

标签: htmlcss

解决方案


听起来像是 flexbox 的工作。其中之一对您有用吗? https://codepen.io/anon/pen/VEpbjv

HTML

  <ul class="flex-container space-between">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
</ul>

<ul class="flex-container space-around">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
</ul>

<ul class="flex-container space-evenly">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
</ul>

CSS

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;
}

.flex-start { 
  justify-content: flex-start; 
}

.flex-end { 
  justify-content: flex-end; 
}  
.flex-end li {
  background: gold;
}

.center { 
  justify-content: center; 
}  
.center li {
  background: deepskyblue;
}

.space-between { 
  justify-content: space-between; 
}  
.space-between li {
  background: lightgreen;
}

.space-around { 
  justify-content: space-around; 
}
.space-around li {
  background: hotpink; 
}

.space-evenly { 
  justify-content: space-evenly; 
}
.space-evenly li {
  background: #bada55; 
}

.flex-item {
  background: tomato;
  padding: 5px;
  width: 60px;
  height: 50px;
  margin: 5px;
  line-height: 50px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
}

推荐阅读