html - 使用 flexbox 水平居中内容

标签 html css alignment flexbox

<分区>

我正在努力将容器中的一些内容水平居中:

https://jsfiddle.net/y56t31q9/6/

.container {
  display: flex;
  flex-direction: column;
  width: 600px;
  background-color: blue;
  justify-content: center;
  /* Not centering content horizontally? */
}
.item {
  max-width: 500px;
  height: 100px;
  background-color: yellow;
  border: 2px solid red;
}
<div class="container">
  <div class="item"></div>
  <section class="item"></section>
  <section class="item"></section>
  <footer class="item"></footer>
</div>

我原以为 justify-content 会成功,但无济于事。

任何帮助将不胜感激 谢谢!

最佳答案

属性 justify-content:center 沿 flex 方向对齐 flex-items - 使用 align-items:center - 参见下面的演示:

.container {
  display: flex;
  flex-direction: column;
  width: 600px;
  background-color: blue;
  justify-content: center;
  align-items:center;/*NEW*/
}
.item {
  max-width: 500px;
  width: 250px;/*NEW*/
  height: 100px;
  background-color: yellow;
  border: 2px solid red;
}
<div class="container">
  <div class="item"></div>
  <section class="item"></section>
  <section class="item"></section>
  <footer class="item"></footer>
</div>

引用:Flexbox W3C spec

下面是当 flex-directionrow 时应用的图像:

image

一个。主轴对齐:对齐内容

横轴对齐:对齐项

flex-directionrow 时,主轴是水平的,但当它是 column 时,则相反.

关于html - 使用 flexbox 水平居中内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40631393/

相关文章:

DIV 容器内的 HTML 图像底部对齐

jquery - 在调整大小时对齐表格单元格内的 div 标签

html - 如何在一条线上垂直居中图像?

javascript - 将服务器数据添加到 index.html

Javascript if 语句使用 :checked and . 绑定(bind)但只有一个选项有效

html - 为什么我的 pdf 链接不起作用?

html - 使用相同的 html/css 编码布局消失

javascript - 如何在html输入中的四个字符后插入空格?

html - 计算的字体大小和 CSS 定义的字体大小之间的字体大小差异?

html - 不应该出现的新行