制作两个弹性项目,每个父项的高度为50%

And*_*tch 3 html css css3 flexbox

我正在使用css flex布局来构建仪表板,并希望在Flex项目中放置两个小部件(一个在另一个之上),并使它们始终保持父级的50%高度(无论内容如何).所以,如果我的HTML是:

<div class="flex-container">
  <div class="flex-item">
    <div class="widget" id="w1">
      widget 1 content
    </div>
    <div class="widget" id="w2">
      widget 2 content
    </div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我的css看起来像:

.flex-container {
  display: flex;
  flex-direction: column;
}
.flex-item {
  flex: 1;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能让两个.widget人总是占据50%的高度.flex-item

我试过了:

.flex-item {
  flex: 1;
  display: flex;
}
.widget {
  flex: 1;
}
Run Code Online (Sandbox Code Playgroud)

但这只适用于两个小部件中的内容相同的情况.

我已经编写了一个更精细的jsfiddle来更好地说明我的问题.

提前致谢!

Mic*_*l_B 5

当你说flex: 1 只有在两个小部件中的内容相同时才有效,这是不正确的.那会破坏目的flex: 1.

flex: 1告诉flex项目在它们之间均匀分配容器空间.如果有四个弹性项目flex: 1,则每个将占25%.三人占33.33%.两个弹性项目将占50%.这与内容数量无关.

看这个插图:DEMO


您在问题中发布的代码中不清楚您遇到的问题.但是,这在您的小提琴演示中很明显.

你有一个主容器height: 400px.您还有一条规则为您的div添加10px填充全能.这为每个div增加了20px的高度.你也有一个标题height: 2em.

当您考虑到布局工作的额外高度时.

尝试这些调整:

HTML(无变化)

CSS

div {
    box-shadow: inset 0 0 0 1px rgba(30, 100, 200, 0.5);
    padding: 10px;                    /* sneaky villain */
    font-family: arial;
}

h1, p { margin: 0; }

#main-wrapper {
    height: 400px;                    /* primary height */
    display: flex;
    flex-direction: column;
}

#header {
    flex-shrink: 0;
    height: 2em;                      /* header height */
}

#main-column-wrapper {
    flex: 1;
    display: flex;
    flex-direction: row;
    height: calc(100% - 2em - 20px);  /* primary height - header height - padding */
}

#side-column {
    width: 20%;
    flex-shrink: 0;
}

#main-column {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: calc(100% - 40px);      /* main-column-wrapper height - padding (2 divs) */
}

#widget1,
#widget2 {
    flex: 1;
    flex-shrink: 0;
    overflow: auto;
}
Run Code Online (Sandbox Code Playgroud)

修改小提琴

另一种选择是用于box-sizing: border-box调整填充.在此处了解更多信息:https://css-tricks.com/box-sizing/