如何使用flexbox垂直居中并强制自动换行?

时间:2016-10-29 18:23:34

标签: html css css3 flexbox centering

我想垂直居中primary__wraper,但它不起作用。

我也想强制自动换行。目前,“częscizamienne”并排出现。

如何将一个向下推到第二行。我的意思是“zamienne”到第二行。

here is a codepen demo

HTML代码

  <section class="primary">
    <div class="primary__wraper">
        <figure>
            <img src="../build/img/ikona_klucz.png" alt="">
            <figcaption>serwis</figcaption>
        </figure>

        <figure>
            <img src="../build/img/box_icon.png" alt="">
            <figcaption>częsci zamienne</figcaption>
        </figure>
    </div>
</section>

和SASS代码

.primary {
background: -webkit-linear-gradient(top, rgb(10,198,162) 0%,rgb(0,160,175) 100%);
height: 500px;
width: 100%;

&__wraper {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    figure {
        img {
            width: 100px;
        }

        figcaption {
            font-family: $font;
            text-transform: uppercase;
            font-weight: 700;
            @include font-size(30px);
            text-align: center;
            color: rgb(255,255,255);
            padding-top: 10px;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

使用内联Css或提供不同的类进行自动换行。

&#13;
&#13;
.primary {
background: -webkit-linear-gradient(top, rgb(10,198,162) 0%,rgb(0,160,175) 100%);
height: 500px;
width: 100%;

&__wraper {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    figure {
        img {
            width: 100px;
        }

        figcaption {
            font-family: $font;
            text-transform: uppercase;
            font-weight: 700;
            @include font-size(30px);
            text-align: center;
            color: rgb(255,255,255);
            padding-top: 10px;
          
          
        }
      
    }
  
}
    
  
&#13;
<section class="primary">
    <div class="primary__wraper">
        <figure>
            <img src="../build/img/ikona_klucz.png" alt="">
            <figcaption>serwis</figcaption>
        </figure>

        <figure>
            <img src="../build/img/box_icon.png" alt="">
            <figcaption style="width:64px;word-wrap: break-word;">częsci zamienne</figcaption>
        </figure>
    </div>
</section>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

Flex容器可以使用flex属性来对齐元素(也称为“flex项目”)。

您想要垂直居中的元素(primary__wraper)是一个弹性容器,但不是一个弹性项目。

垂直居中primary__wraper的一种简单方法是将父级设为灵活容器。

.primary {
    display: flex;              /* new */
    justify-content: center;    /* new */
    align-items: center;        /* new */
    background: -webkit-linear-gradient(top, rgb(10,198,162) 0%,rgb(0,160,175) 100%);
    height: 500px;
    width: 100%;
}

现在,flex对齐属性适用于孩子。

我还添加了适用于text-align: center元素子项的figure,并更正了HTML中的错误:您的<figure="primary__figure">应为<figure class="primary__figure">。它现在可以被CSS作为目标。

revised codepen

相关问题