html - 垂直和水平居中,同时遵守 flexbox 的 html 规则

标签 html css flexbox

我正在尝试制作类似于 Bootstraps 的东西 jumbotron使用 flexbox 的类。我希望所有内容都垂直和水平居中,但我希望框内的所有内容仍然遵守标准 HTML 规则。也就是说,如果我制作一个 <h1>然后是 <h4>我希望它们在不同的行上;然而,使用我当前的 flexbox 属性,这并没有发生。请参见下面的示例——它看起来像 titlesubtitle而不是 title\nsubtitle

.Jumbotron {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}
<div class="Jumbotron">
  <h1>title</h1>
  <h4>subtitle</h4>
</div>

最佳答案

您可以引入一个新的非 flex 父元素来包裹这些元素,这样父元素将成为居中的 flex 子元素,而它的子元素将只是普通的非 flex 元素

.Jumbotron {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}
<div class="Jumbotron">
  <div>
    <h1>title</h1>
    <h4>subtitle</h4>
  </div>
</div>

或者对于您的示例,如果您只想让 flex 父级的子级在他们自己的行上,请使用 flex-direction: column;

.Jumbotron {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  flex-direction: column;
}
<div class="Jumbotron">
  <h1>title</h1>
  <h4>subtitle</h4>
</div>

关于html - 垂直和水平居中,同时遵守 flexbox 的 html 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42055586/

相关文章:

css - 复杂的柔性盒。 child 到 flex-end,但首先 flex-start 垂直

.net - 如果javascript被禁用,如何在服务器上检查?

javascript - src 的图像选择不起作用 jquery

javascript - 动态将其值设置为 true 后,复选框未显示为选中状态

javascript - 溢出 :auto is not working on a BlackBerry device

html - 如何使我的 flexbox 导航在底部没有背景被截断?

html - 使用 flexbox CSS 的左列和堆叠右列

javascript - 递归设置 `display: none`,特定元素除外

javascript - background-position-x + 动画从右到左 + IE

html - flex 盒子内的元素不符合要求的大小