2014-11-04 43 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