如何在 div、水平和垂直方向上对齐元素与 Flex



如何将一个div居中到另一个div?图像呢?我希望它垂直和水平居中。我想变得现代并使用flex - 我不在乎旧的IE支持。

.outside {
  background: orange;
  width: 400px;
  height: 300px;
}
.inside {
  width: 80%;
  background: yellow;
}
<div class='outside'>
  <div class='inside'>
    This is the inside div that I would like to center in the outer one
  </div>
</div>
---------------------------------------------------------------------------
<div class='outside'>
  <img src="http://placehold.it/350x150">
</div>

在CSS中垂直居中总是比它应该的更棘手。这是一个使用 Flex 的简单解决方案。Flex 并非在所有浏览器中都有效!

需要宽度才能水平居中。

我知道有很多类似的问题,但我相信这种方法既快速又简单。

.outside {
  background: orange;
  width: 400px;
  height: 300px;
  
  /* This is the magic*/
  display: flex;
  justify-content: center; /* This centers horizontally */
  align-items: center; /* This centers vertically */
}
.inside {
  width: 80%; /* Without a width, horizontally aligning "doesn't work"*/ 
  background: yellow;
}
<div class='outside'>
  <div class='inside'>
    This is the inside div that I would like to center in the outer one
  </div>
</div>
---------------------------------------------------------------------------
<div class='outside'>
  <img src="http://placehold.it/350x150">
</div>

最新更新