无法使用flexbox垂直居中项目

时间:2016-06-06 00:24:18

标签: html css css3 flexbox

我正在尝试使用flexbox .parent_test { display: flex; justify-content: center; align-items: center; } .sk-double-bounce { width: 40px; height: 40px; position: relative; } .sk-double-bounce .sk-child { width: 100%; height: 100%; border-radius: 20%; background-color: green; position: absolute; top: 0; left: 0; -webkit-animation: sk-doubleBounce 2s infinite ease-in-out; animation: sk-doubleBounce 2s infinite ease-in-out; } .sk-double-bounce .sk-double-bounce2 { -webkit-animation-delay: -1.0s; animation-delay: -1.0s; } @-webkit-keyframes sk-doubleBounce { 0%, 100% { -webkit-transform: scale(0); transform: scale(0); } 50% { -webkit-transform: scale(1); transform: scale(1); } } @keyframes sk-doubleBounce { 0%, 100% { -webkit-transform: scale(0); transform: scale(0); } 50% { -webkit-transform: scale(1); transform: scale(1); } }进行水平和垂直居中处理({em>点击“水平和垂直两者”=&gt;然后点击“你能使用flexbox吗?”< / em>的)

  <h1><a href="https://css-tricks.com/centering-css-complete-guide/#both-flexbox">centering-css-complete-guide/#both-flexbox</a>
  <div class="parent_test">
      <div class="sk-double-bounce">
        <div class="sk-child sk-double-bounce1"></div>
        <div class="sk-child sk-double-bounce2"></div>
      </div>
  </div>
{{1}}

但为什么不垂直居中? Here

2 个答案:

答案 0 :(得分:2)

您需要为父级指定height,以使其垂直对齐。

&#13;
&#13;
body {
  margin: 0
}
.parent_test {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh
}
.sk-double-bounce {
  width: 40px;
  height: 40px;
  position: relative;
}
.sk-double-bounce .sk-child {
  width: 100%;
  height: 100%;
  border-radius: 20%;
  background-color: green;
  position: absolute;
  top: 0;
  left: 0;
  -webkit-animation: sk-doubleBounce 2s infinite ease-in-out;
  animation: sk-doubleBounce 2s infinite ease-in-out;
}
.sk-double-bounce .sk-double-bounce2 {
  -webkit-animation-delay: -1.0s;
  animation-delay: -1.0s;
}
@-webkit-keyframes sk-doubleBounce {
  0%, 100% {
    -webkit-transform: scale(0);
    transform: scale(0);
  }
  50% {
    -webkit-transform: scale(1);
    transform: scale(1);
  }
}
@keyframes sk-doubleBounce {
  0%, 100% {
    -webkit-transform: scale(0);
    transform: scale(0);
  }
  50% {
    -webkit-transform: scale(1);
    transform: scale(1);
  }
}
&#13;
<div class="parent_test">
  <div class="sk-double-bounce">
    <div class="sk-child sk-double-bounce1"></div>
    <div class="sk-child sk-double-bounce2"></div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您检查输出,您会看到.sk-double-bounce实际上位于.parent_test内。问题是.parent_test的高度较低。 (它只需要内容所需的高度加上填充和边框值。)

您现在可以理解为什么@dippas的解决方案有效。如果需要,可以删除.parent_test包装器,将flex规则放在body中,将body的高度设置为100vh,然后直接放置.sk-double-bounce div在体内。那会做同样的工作。