如何使用flexbox在容器内水平和垂直居中放置div.在下面的示例中,我希望每个数字都位于彼此下方(成行),水平居中.

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;
  align-items: center;
  justify-content: center;
}
row {
  width: 100%;
}
.flex-item {
  background: tomato;
  padding: 5px;
  width: 200px;
  height: 150px;
  margin: 10px;
  line-height: 150px;
  color: white;
  font-weight: bold;
  font-size: 3em;
  text-align: center;
}
<div class="flex-container">
  <div class="row">
    <span class="flex-item">1</span>
  </div>
  <div class="row">
    <span class="flex-item">2</span>
  </div>
  <div class="row">
    <span class="flex-item">3</span>
  </div>
  <div class="row">
    <span class="flex-item">4</span>
  </div>
</div>

http://codepen.io/anon/pen/zLxBo

推荐答案

我想你想要下面这样的东西.

html, body {
    height: 100%;
}
body {
    margin: 0;
}
.flex-container {
    height: 100%;
    padding: 0;
    margin: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}
.row {
    width: auto;
    border: 1px solid blue;
}
.flex-item {
    background-color: tomato;
    padding: 5px;
    width: 20px;
    height: 20px;
    margin: 10px;
    line-height: 20px;
    color: white;
    font-weight: bold;
    font-size: 2em;
    text-align: center;
}
<div class="flex-container">
    <div class="row"> 
        <div class="flex-item">1</div>
        <div class="flex-item">2</div>
        <div class="flex-item">3</div>
        <div class="flex-item">4</div>
    </div>
</div>

见演示:http://jsfiddle.net/audetwebdesign/tFscL/

如果你想让高度和顶部/底部填充正常工作,你的.flex-item个元素应该是块级别(div而不是span).

此外,在.row上,将宽度设置为auto,而不是100%.

你的.flex-container处房产都很好.

如果希望.row在视口中垂直居中,请将.row%高度指定给htmlbody,并将body的页边距设为零.

请注意,.flex-container需要一个高度才能看到垂直对齐效果,否则,容器会计算包围内容所需的最小高度,该高度小于本例中的视口高度.

Footnote:
The flex-flow, flex-direction, flex-wrap properties could have made this design easier to implement. I think that the .row container is not needed unless you want to add some styling around the elements (background image, borders and so on).

一个有用的资源是:http://demo.agektmr.com/flexbox/

Html相关问答推荐

如何将数据发送到Flask 应用程序中的表单文本框

悬停时放大人物:不要增加其周围边界的大小

放大缩小标题在外面的图像

禁用与行分开的边框折叠span

如何让QML`Text`元素内的链接在悬停时显示鼠标指针?

在元素之间添加空格

在 Select 前后更改选项卡的背景

如何在htmlAngular 17的@for中使用索引

如何防止可见的滑动抽屉,同时转移HTML方向?

我怎样才能在我的网站上制作花哨的角落

滚动平滑在笔记本电脑上不起作用,但在Nextjs网站的手机浏览器中起作用

Html视频标签:圆角像素化

如何将功能附加到嵌入式药剂中的按钮?

如何防止弹性项目溢出容器?

网格布局中的组件

在Firefox中使用keySplines时,SVG: <animateMotion>不起作用

白色栏超出页面100%的右侧

CSS 随着内容宽度的增加而减少填充

如何删除输入中输入类型数字中的箭头?

Header 或 P 标记中的填充不能与 em 单元一起正常工作