使用flexbox在两列布局中使用共享标头拉伸列

时间:2018-06-14 05:59:06

标签: html css css3 flexbox

我正在使用flexbox创建带有标题行的两列布局。

* {
  box-sizing: border-box;
  position: relative;
}

.container {
  border: 2px solid gray;
  display: flex;
  flex-wrap: wrap;
  height: 300px;
}

.header {
  flex-basis: 100%;
  border: 2px solid magenta;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.column1 {
  flex-basis: 150px;
  /* height: calc(100% - 50px); */
  border: 2px solid green;
}

.column2 {
  /* height: calc(100% - 70px); */
  flex: 1;
  border: 2px solid orange;
}
<div class='container'>
  <div class='header'>it's a header</div>
  <div class='column1'>column 1</div>
  <div class='column2'>column 2</div>
</div>

随意查看完整示例here

正如您在示例中所看到的,列和标题之间存在间隙。我的目标是垂直拉伸色谱柱以填充容器中的整个空白区域。 我可以通过设置height属性calc(100% - <header-height>)来实现它。这是正确的方法吗?

我只是尝试使用“flex”样式并将align-items: stretch设置为容器,将align-self: stretch设置为列,但没有成功。我可能错过了试图以这种方式实现它的东西吗?

2 个答案:

答案 0 :(得分:2)

我认为在这种情况下将flex-direction指定为column是合适的。 第二行本身是flex元素,flex-direction: row。您可以使用flex: 1填充余下的剩余空间,相当于flex-grow: 1

* {
  box-sizing: border-box;
}

.container {
  border: 2px solid gray;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 300px;
}

.header {
  border: 2px solid magenta;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.subcontainer {
  display: flex;
  flex-direction: row;
  flex: 1;
}

.column1 {
  flex-basis: 150px;
  border: 2px solid green;
}

.column2 {
  flex: 1;
  border: 2px solid orange;
}
<div class='container'>
  <div class='header'>it's a header</div>
  <div class="subcontainer">
    <div class='column1'>column 1</div>
    <div class='column2'>column 2</div>
  </div>
</div>

答案 1 :(得分:1)

如下所示

* {
  box-sizing: border-box;
}

body,
html {
  height: 100%;
}

.container {
  border: 2px solid gray;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.header {
  width: 100%;
  border: 2px solid magenta;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.body-container {
  display: flex;
  width: 100%;
  flex: 1;
}

.column1 {
  width: 50%;
  border: 2px solid green;
}

.column2 {
  width: 50%;
  border: 2px solid orange;
}
<div class='container'>
  <div class='header'>it's a header</div>
  <div class="body-container">
    <div class='column1'>column 1</div>
    <div class='column2'>column 2</div>
  </div>

</div>