将旧布局转换为flexbox

时间:2015-04-18 09:35:49

标签: html css flexbox

目前我有这种布局。



    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }
    html,
    body {
      height: 100%;
      min-height: 100%;
    }
    #wrapper {
      height: 100%;
      min-height: 100%;
      position: relative;
      background-color: red;
    }
    header {
      height: 100%;
      min-height: 100vh;
      position: relative;
      background-color: green;
      text-align: center;
    }
    #header-top {
      position: fixed;
      left: 0;
      right: 0;
      top: 0;
      width: 100%;
      outline: 1px dotted red;
      background-color: blue;
    }
    #header-middle {
      position: relative;
      top: 50%;
      transform: translateY(-50%);
      background-color: yellow;
      outline: 1px dotted red;
    }
    #header-bottom {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      width: 100%;
      background-color: grey;
      outline: 1px dotted red;
    }

<div id="wrapper">
  <header>
    <div id="header-top">
      <p>I am fixed at the top</p>
    </div>
    <div id="header-middle">
      <p>I am vertically centered</p>
    </div>
    <div id="header-bottom">
      <p>I am stuck at the bottom but not fixed</p>
    </div>
  </header>
</div>
&#13;
&#13;
&#13;

如何在此处使用flexbox来获得相同的布局。

  • html,body和#wrapper需要以可视方式展开以包围所有子元素。
  • 标题是填充整个视口。
  • #header-top固定在顶部,包含一个浮动到左边的徽标,导航浮动到右边,没有明确的高度。
  • #header-middle将在标题内垂直居中。
  • #header-bottom就像粘在底部的粘性页脚,但没有固定。

Fiddle

1 个答案:

答案 0 :(得分:2)

使用此:

header {
  display: flex; /* Magic begins */
  flex-direction: column; /* Stack vertically */
  height: 100%; /* As tall as the containing block */
  justify-content: space-between; /* Distribute the flex items */
}

* {
  padding: 0;
  margin: 0;
}
html, body, header {
  height: 100%;
}
header {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: green;
  text-align: center;
}
header > div {
  outline: 1px dotted red;
}
#header-top {
  background-color: blue;
}
#header-middle {
  background-color: yellow;
}
#header-bottom {
  background-color: grey;
}
<header>
  <div id="header-top">
    <p>I am fixed at the top</p>
  </div>
  <div id="header-middle">
    <p>I am vertically centered</p>
  </div>
  <div id="header-bottom">
    <p>I am stuck at the bottom but not fixed</p>
  </div>
</header>