html - 如何垂直排列 flex 容器内的元素?

标签 html css flexbox

我有以下代码:

<section class="body1">
    <h1 class="text1">Tours around the world</h1>
    <h3 class="text1">Great experiences</h3>
    <form action="/respuestaUsuario/">
        <input type="text" placeholder="Where are you going?">
    </form>
</section>

及其对应的CSS

.body1 {
    display: flex;
    align-items: center;
    background-size: 100% 100%;
    background-image: url("../images/poolpic2.png");
}

我希望三个元素(h1、h3 和表单)在垂直方向上一个接一个。然而,它们一个接一个地水平出现。

我希望它们在容器的中心,并且行

align-items: center;

实际上帮助它们位于中心,但它们又不是像我希望的那样一个接一个垂直排列。元素基本上是这样的:

    h1------------h3-------------form

但我想要他们

-------------h1-------------
-------------h3-------------
------------form------------

最佳答案

您正在寻找的是 flex-directionjustify-contentalign-items 属性。特别是 flex-direction: column;justify-content: center;align-items: center;

flex-direction: column; 指定您希望元素(子项)具有垂直方向。

justify-content: center; 将元素在主轴上水平居中。

align-items: center; 使元素在横轴上垂直居中。

.body1 {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-size: 100% 100%;
  /* para que se ajuste el tamano de la imagen al contenedor */
  background-image: url("../images/poolpic2.png");
}
<section class="body1">

  <!-- <img src="./assets/images/poolpic2.png" alt="pool-pic"> -->
  <h1 class="text1">Tours around the world</h1>
  <h3 class="text1">Great experiences</h3>
  <form action="/respuestaUsuario/">
    <input type="text" placeholder="Where are you going?">
  </form>
</section>

关于html - 如何垂直排列 flex 容器内的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57763579/

相关文章:

html - 将品牌图像作为标题添加到 html 页面

Javascript hide show div - 默认情况下显示 div

javascript - CSS/JS 滚动故障效果(性能)

html - 如何在 bootstrap 4 中删除页脚后的间隙?

html - 为什么带有 clearfix 的 inline-flex 元素有一个奇怪的空白?

html - CSS border-bottom 在元素之间获取空间

javascript - PHP 表单在我将其与我的本地主机链接后无法验证(使用 MySQL 和 PHP)

css - 在 foursquare.com 上执行 'Recent Activity' 效果的页面小部件或插件?

html - Flexbox 元素不收缩

html - 如何在 bootstrap 4 的容器中垂直和水平居中放置文本?