<分区>
<分区>
如何将一个 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>
关于html - 如何使用 Flex 水平和垂直对齐 div 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43308987/