vertical-align:middle对我不起作用?

时间:2018-01-29 23:27:24

标签: html css css3 flexbox

我不知道为什么左边的div与中心垂直对齐。 这是html:

<body >
    <div id="topH" class="vertCenter-flex">
        <div id="profileBox" class="bgc-green divmain centerItems" >
            <p>p1</p>
            <p>p2</p>
            <p>lala</p>
        </div>
        <div id="offers" class="bgc-blue divmain" ></div>
        <div id="news" class="bgc-purple divmain"></div>
    </div>
</body>

这是必要的css:

.bgc-blue{
    background-color: #0066ff;
}
.bgc-white{
    background-color: whitesmoke;
}
.bgc-purple{
    background-color: purple;
}
.bgc-green{
    background-color: rgb(70, 223, 70);
}
.vertCenter-flex{
    display: flex;
    align-content: center;
    justify-content: center;
}
.divmain{
    margin-top: 10px;
    display:  inline-block;
    vertical-align: -webkit-baseline-middle;
    height: 95%;
}
.centerItems{
    text-align: center;
}
#topH{
    width: 100%;
    height: 95%;
}
#offers{
    width: 40%;
    margin-left: 10px;
    margin-right: 10px;
}
#profileBox{
    width: 30%;
    height: fit-content;
}
#news{
    width: 25%;
}

这是输出。再说一遍,我不知道还能做些什么来使左侧div垂直居中(#profileBox) enter image description here

2 个答案:

答案 0 :(得分:2)

为此目的在flex容器上使用align-items: center;

&#13;
&#13;
.bgc-blue {
  background-color: #0066ff;
}

.bgc-white {
  background-color: whitesmoke;
}

.bgc-purple {
  background-color: purple;
}

.bgc-green {
  background-color: rgb(70, 223, 70);
}

.vertCenter-flex {
  display: flex;
  align-content: center;
  justify-content: center;
  align-items: center;
}

.divmain {
  margin-top: 10px;
  display: inline-block;
  vertical-align: -webkit-baseline-middle;
  height: 95%;
}

.centerItems {
  text-align: center;
}

#topH {
  width: 100%;
  height: 95%;
}

#offers {
  width: 40%;
  margin-left: 10px;
  margin-right: 10px;
  background: #fa0;
  height: 300px;
}

#profileBox {
  width: 30%;
  height: fit-content;
}

#news {
  width: 25%;
  background: #0fa;
  height: 300px;
}
&#13;
<body>
  <div id="topH" class="vertCenter-flex">
    <div id="profileBox" class="bgc-green divmain centerItems">
      <p>p1</p>
      <p>p2</p>
      <p>lala</p>
    </div>
    <div id="offers" class="bgc-blue divmain">content</div>
    <div id="news" class="bgc-purple divmain">content</div>
  </div>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

更改你的CSS

.vertCenter-flex {
  display: flex;
  align-content: center;
  justify-content: center;
  align-items: center;
  flex-direction:column;
}