如何在Flex容器内垂直排列元素?

时间:2019-09-02 23:47:16

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

3 个答案:

答案 0 :(得分:2)

您要寻找的是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>

答案 1 :(得分:0)

通常,如果您将显示模式设置为“ flex”(display:flex),则即使未在CSS中键入,“ flex-direction”的默认值也是“ row”。因此,您可以添加“ flex-direction:column”来更改默认值,并且元素可以在垂直方向上是一个接一个。

答案 2 :(得分:0)

首先给div.body1 display: flex,其中flex-flow: columnalign-items: center水平居中。接下来给html, body, and div.body1一个height: 100%,最后给div.body1一个align-items:center以使其垂直居中:

html, body, .body1{
   height: 100%;
}

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

h1{
   margin-top: 0;
}
<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>

相关问题