CSS将项目保留在中心,边距为

时间:2018-06-06 06:27:02

标签: html css

我需要创建一个标签部分。容器应该有固定的填充,当标签包裹到下一行时,它应该与顶行间隔。

问题在于当它包裹到下一行时,它不再与中心对齐。如何保持线条与固定填充物之间的间距?



.flex {
  display: flex;
}

.align-center {
  align-items: center;
}

.wrap {
  flex-wrap: wrap;
}

section {
  border: 1px solid grey;
  min-height: 40px;
  width: 400px;
  padding: 0 0.5em;
}

.item {
  background-color: hotpink;
  padding: 0.3em;
  margin-right: 0.4em;
  margin-bottom: 0.3em;
}

* {
  box-sizing: border-box;
}

<section class="flex align-center wrap">

  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>

</section>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

margin-top: 0.3em添加到子div

&#13;
&#13;
.flex {
  display: flex;
}

.align-center {
  align-items: center;
}

.wrap {
  flex-wrap: wrap;
}

section {
  border: 1px solid grey;
  min-height: 40px;
  width: 400px;
  padding: 0 0.5em;
}

.item {
  background-color: hotpink;
  padding: 0.3em;
  margin-right: 0.4em;
  margin-bottom: 0.3em;
  margin-top: 0.3em;
}

* {
  box-sizing: border-box;
}
&#13;
<section class="flex align-center wrap">

  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>

</section>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你需要定义相同的 top&amp; padding 容器的底部 .flex,这将始终保持.item s 垂直居中,然后只需调整 margin即可在它们之间实现等间距

&#13;
&#13;
* {box-sizing: border-box}

.flex {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  border: 1px solid grey;
  min-height: 40px;
  width: 400px;
  padding: .5em .2em;
  animation: width 4s linear infinite alternate;
}

.item {
  background-color: hotpink;
  padding: .3em;
  margin: .2em;
}

@keyframes width {to {width: 100px}}
&#13;
<section class="flex">
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
</section>
&#13;
&#13;
&#13;