如何将div高度100%设置为带有flex的容器,并保持垂直对齐?

时间:2016-12-06 11:38:32

标签: html css css3 flexbox

我尝试使用flexbox对文本和按钮进行居中,并保持列平等。但是我很难将列高设置为100%到容器。当我将高度设置为100%时,它的垂直对齐不再在中间。我不想使用表格或javascript来实现结果。

.container {
  display:flex;
  border-top: solid 1px;
  border-bottom: solid 1px;
  align-items: center;
  height:48px;
}
.column {
  flex-basis:100%;
  text-align:center;
}
.mid-col {
  border-left:solid 1px;
  border-right:solid 1px;
}
<div class="container">
  <div class="column">
    <div>50</div>
    <div>Following</div>
  </div>
  <div class="column mid-col">
    <div>50</div>
    <div>Followers</div>
  </div>
  <div class="column">
    <button>Follow</button>
  </div>  
</div>

JS小提琴:fiddle

2 个答案:

答案 0 :(得分:1)

如果您希望column获得100%container的高度,则必须使用嵌套的flexbox - 添加:

  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

column并从align-items: center移除container(以便默认align-items: stretch生效)。

(您现在无法为column设置100%的高度,因为align-items: center已应用container

见下面的演示:

.container {
  display: flex;
  border-top: solid 1px;
  border-bottom: solid 1px;
  height: 48px;
}
.column {
  flex-basis: 100%;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.mid-col {
  border-left: solid 1px;
  border-right: solid 1px;
}
<div class="container">
  <div class="column">
    <div>50</div>
    <div>Following</div>
  </div>
  <div class="column mid-col">
    <div>50</div>
    <div>Followers</div>
  </div>
  <div class="column">
    <button>Follow</button>
  </div>
</div>

答案 1 :(得分:0)

只需将display: table用于父级,display: table-cell; vertical align: middle;用于子级,即可在不使用表的情况下实现此目的。如果你想使用flex本身,我已经在下面的例子中实现了它。

<!doctype html>
<html>

<head>
    <style>
        .container {
            border-top: solid 1px;
            border-bottom: solid 1px;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 300px;
        }
        
        .column {
            text-align: center;
            width: 33%;
        }
        
        .column--top {
            align-self: flex-start;
        }
        
        .column--bottom {
            align-self: flex-end;
        }
        
        .mid-col {
            border-left: solid 1px;
            border-right: solid 1px;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="column">
            <div>50</div>
            <div>Following</div>
        </div>
        <div class="column mid-col">
            <div>50</div>
            <div>Followers</div>
        </div>
        <div class="column">
            <button>Follow</button>
        </div>
    </div>

</body>

</html>