Flexbox - 具有垂直居中内容的分隔符

时间:2018-02-26 20:08:59

标签: html css css3 flexbox

所以我有一个容器,我希望从左到右均匀地分隔东西并垂直居中。如果内容变得更长,我还想在内容之间添加垂直分隔符。

如果内容不是垂直居中的话,这个分隔符可以正常工作:



section {
  display: flex;
  flex-direction: row;
  flex: 1;
  margin: 0 -8px;
}

section > * {
  margin: 0 8px;
}

.divider {
  width: 2px;
  margin: 6px 0;
  background: blue;
}

.item {
  flex: 1;
  background: orange;
}

<section>
  <div class="item">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
  </div>
  <div class="divider"></div>
  <div class="item">
    <p>Potato</p>
  </div>    
  <div class="divider"></div>
  <div class="item">
    <p>Markup</p>
  </div>
</section>
&#13;
&#13;
&#13;

但是当我添加align-items: center;时,分隔符会消失。

&#13;
&#13;
section {
  display: flex;
  flex-direction: row;
  flex: 1;
  margin: 0 -8px;
  align-items: center;
}

section > * {
  margin: 0 8px;
}

.divider {
  width: 2px;
  margin: 6px 0;
  background: blue;
}

.item {
  flex: 1;
  background: orange;
}
&#13;
<section>
  <div class="item">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
  </div>
  <div class="divider"></div>
  <div class="item">
    <p>Potato</p>
  </div>    
  <div class="divider"></div>
  <div class="item">
    <p>Markup</p>
  </div>
</section>
&#13;
&#13;
&#13;

如何取回分隔线并使我的内容垂直居中?

1 个答案:

答案 0 :(得分:3)

设置align-items: center时,弹性项目的高度由其内容决定,因此您可以在align-self: stretch元素上使用divider

您还可以在align-self: center元素上使用item,并从flex-container中删除align-items: centerDEMO

你可以对边距DEMO做同样的事情

&#13;
&#13;
section {
  display: flex;
  flex-direction: row;
  flex: 1;
  margin: 0 -8px;
  align-items: center;
}
section>* {
  margin: 0 8px;
}
.divider {
  width: 2px;
  margin: 6px 0;
  background: blue;
  align-self: stretch;
}
.item {
  flex: 1;
  background: orange;
}
&#13;
<section>
  <div class="item">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
  </div>
  <div class="divider"></div>
  <div class="item">
    <p>Potato</p>
  </div>
  <div class="divider"></div>
  <div class="item">
    <p>Markup</p>
  </div>
</section>
&#13;
&#13;
&#13;