2014-11-04 42 views
1

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

I.e.像:

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>

回答

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

+0

很酷,谢谢。 – 2014-11-04 15:15:54