首页 > 解决方案 > flexbox 让内容消失

问题描述

我正在使用 flexbox 来掌握它的窍门,但我遇到了一些问题。我的目标是让窗口由四种背景颜色分隔,其中第一种只是标题行,然后页面的其余部分由 3 列填充,每列具有不同的背景颜色。但是由于某种原因,如果我写 display: flex 它什么也不显示。有人可以向我解释如何获得这种预期的效果吗?

   .container {
  width: 100%;
  height: 100%;
}

.header {
  height: 150px;
  background-color: red;
}
.col-container {
  widows: auto;
  height: auto;
  display: flex;
  flex-direction: row;
}
.col {
  flex: 1;
}
.col-container:nth-child(1) {
  background: green;
}
.col-container:nth-child(2) {
  background: blue;
}
.col-container:nth-child(3) {
  background: yellow;
}
<body>
  <div class="container">
    <div class="header"></div>
    <div class="col-container">
      <div class="col"></div>
      <div class="col"></div>
      <div class="col"></div>
    </div>
  </div>
</body>

标签: cssflexbox

解决方案


这是一个工作示例:

.container {
  width: 100%;
  height: 100%;
}

.header {
  height: 150px;
  background-color: red;
}

.col-container {
  widows: auto;
  height: auto;
  display: flex;
  flex-direction: row;
}

.col-1 {
  flex: 1 1 33.333%;
  background-color: green;
}

.col-2 {
  flex: 1 1 33.333%;
  background-color: blue;
}

.col-3 {
  flex: 1 1 33.333%;
  background-color: yellow;
}
<body>
  <div class="container">
    <div class="header"></div>
    <div class="col-container">
      <div class="col-1">ts</div>
      <div class="col-2">dtd</div>
      <div class="col-3">dt</div>
    </div>
  </div>
</body>

这是您需要解决的问题:

  1. 设置flex-directionrow。您很可能希望这些列彼此相邻。
  2. 将和的类添加到您的 HTMLcol-1中。col-2col-3
  3. 您需要这些col课程中的内容,否则您将什么也看不到。

我将 a flex-basis(速记中的第三个参数flex)设置为 33.333%。您不一定需要这个,但很高兴看到特定元素将填充或更改多少空间。

编辑对于评论:

body {
  margin: 0;
  padding: 0;
}

.container {
  width: 100%;
  height: 100%;
}

.header {
  height: 150px;
  background-color: red;
}

.col-container {
  widows: auto;
  height: auto;
  display: flex;
  flex-direction: row;
  height: calc(100vh - 150px);
}

.col-1 {
  flex: 1 1 33.333%;
  background-color: green;
}

.col-2 {
  flex: 1 1 33.3333%;
  background-color: blue;
}

.col-3 {
  flex: 1 1 33.3333%;
  background-color: yellow;
}
<body>
  <div class="container">
    <div class="header"></div>
    <div class="col-container">
      <div class="col-1"></div>
      <div class="col-2"></div>
      <div class="col-3"></div>
    </div>
  </div>
</body>

基本上,你需要给col-container一个高度。为此,我在语句中使用vh了单位。calc它从视口高度中减去标题高度并给出余数。这也消除了填充物含量的必要性。


推荐阅读