html - 如何使用 Flex 水平和垂直对齐 div 中的元素

标签 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>

最佳答案

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

上一篇:javascript - 如何使用 Javascript 打开模式?

下一篇:javascript - 为什么 css/js 分页没有显示在这个页面上?

相关文章:

javascript - 单击用户图像时显示wordpress用户描述

html - 盒子乱七八糟

html - 水平对齐div中的元素

html - 3 列流体 flexbox 和 rtl

html - 如何根据另一个 child 的存在来定位这个 flexbox child ?

html - IE 中的最小高度和 flex

javascript - 为什么 setTimeout 不等待调用函数?

javascript - 如何使用所有元素颜色的变量制作文件

jquery - 在第一句中添加一个元素

css - 当按钮上没有文本时,Primefaces splitButton 呈现问题