如何拉伸flex儿童,使背景颜色与兄弟的高度相匹配

时间:2017-01-31 11:48:37

标签: html css css3 flexbox alignment

我在li中有两个链接,一个带有短或长的文本,另一个是图标。图标的background-color应与文本链接的高度匹配,而文本应定义填充。它不一定是flexbox,我只是觉得它应该更容易。

http://codepen.io/anon/pen/GrQZKN

li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .first {
    background-color: #333;
    padding: 20px;
    color: #fff;
    flex: 1;
  }
  .second {
    background-color: orange;
    align-items: stretch;
    display: flex;
  }
}

<ul>
  <li>
    <a href="#" class="first">Link</a>
    <a href="#" class="second">(icon)</a>
  </li>
  <li>
    <a href="#" class="first">Longer LongerLonger Longer link</a>
    <a href="#" class="second">(icon)</a>
  </li>
</ul>

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

  1. align-items: center移除li拉伸 second

  2. align-items: stretch替换为align-items: center中的li.second垂直对齐

  3. 见下面的演示:

    body {
      max-width: 300px;
      background-color: #ddd;
    }
    
    li {
      display: flex;
      justify-content: space-between;
      /*align-items: center;*/
      border-bottom: 1px solid #eee;
    }
    li .first {
      background-color: #333;
      padding: 20px;
      color: #fff;
      flex: 1;
    }
    li .second {
      background-color: orange;
      align-items: center; /*CHANGED THIS*/
      display: flex;
    }
    <ul>
      <li>
        <a href="#" class="first">Link</a>
        <a href="#" class="second">(icon)</a>
      </li>
      <li>
        <a href="#" class="first">Longer LongerLonger Longer link</a>
        <a href="#" class="second">(icon)</a>
      </li>
    </ul>