使用flex来居中和拉伸背景

时间:2014-11-04 14:55:37

标签: css flexbox

如何将此笑脸水平和垂直居中放置在图像顶部,同时将其拉伸至其容器大小的50%?

即。像:

enter image description here



.test {
    display: flex;
}
.test .smile {
    background-image: url(https://rawgit.com/anonymous/9f37047667b06af42c3d/raw/65a00b0f38b05bb6c96fa827993dbae31fe391b3/test.svg);
    background-repeat: no-repeat;
    justify-content: center;
    align-content: center;
    flex-direction: column;
    height: 50%;
    width: 50%;
}

<div class="test">
    <a>
        <img src="http://lorempixel.com/400/400">
        <span class="smile"></span>
    </a>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

当容器设置了高度时,我才能让flexbox工作。 Here's a fiddle of it working。由于您的对齐图像被设置为背景图像,因此没有简单的方法来设置宽度和高度。如果它是一个图像,你可以很容易地做到50%的宽度,高度可以照顾自己。

.test {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 400px;
    width: 400px;
    background: url(http://lorempixel.com/400/400) no-repeat;
}
.test .smile {
    background-image: url(https://rawgit.com/anonymous/9f37047667b06af42c3d/raw/65a00b0f38b05bb6c96fa827993dbae31fe391b3/test.svg);
    background-repeat: no-repeat;
    display: block;
    width: 100px;
    height: 100px;
}

如果你正在使用svg,你只需要设置.smile类的高度。 Here's an example with an image centered