如何使用flexbox将最后一个元素放在列的末尾?

时间:2017-07-07 19:47:17

标签: css css3 flexbox

我正在尝试使用flexbox来定位垂直导航栏底部的最后一项。有没有办法使用flexbox?

navbar

以下是代码示例:

<!doctype html>
<html>
<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
 ul {
    list-style: none;
    background: red;
    width: 100px;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
 }

 li {
    border: 1px solid blue;
 }

 li:last-child {
    background: blue;
    align-self: end;
 }

</style>
<body>
<ul>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
</ul>
</body>
</html>

1 个答案:

答案 0 :(得分:4)

margin-top: auto会将其推到底部。您可以在此处阅读有关自动边距和弹性框的更多信息 - https://hackernoon.com/flexbox-s-best-kept-secret-bd3d892826b6

<!doctype html>
<html>
<style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  ul {
    list-style: none;
    background: red;
    width: 100px;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  
  li {
    border: 1px solid blue;
  }
  
  li:last-child {
    background: blue;
    margin-top: auto;
  }
</style>

<body>
  <ul>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
    <li>foo</li>
  </ul>
</body>

</html>