如何使用Flex在div,水平和垂直方向上对齐元素

时间:2017-04-09 16:13:14

标签: html css flexbox

如何将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>

1 个答案:

答案 0 :(得分:1)

在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>