2017-02-14 73 views
1

我正在一個網站上工作,我想像你一樣使用背景位置:中心風格背景。對於普通圖像是否有與此相同的內容?相當於背景位置的圖像位置

由於提前,

Luuk

編輯:

的圖像是響應以及包含在容器中。

CSS:

.img-container { 
max-height: 300px; 
overflow: hidden; 
} 

.img-container img { 
max-height: 100%; 
max-width: 100%; 
} 
+0

你能提供你有什麼這麼遠嗎?這將有助於查看您的HTML。 –

回答

2

我會做這樣的事情爲中心的圖像位置。

.img-container { 
    display: flex; 
    justify-content: center; 
    align-items: center; 
    max-height: 300px; 
    overflow: hidden; 
} 

.img-container img { 
    max-height: 100%; 
    max-width: 100%; 
} 
+0

非常感謝!正是我在找什麼。我的圖像和導航欄之間也有一些隨機的空白,現在已經消失。謝謝! :D – Luuxter

+0

@Luuxter這不適用於跨瀏覽器,請牢記這一點。 –

+0

@WarreBuysse我注意到了,謝謝你提醒我。在這種情況下,幸運的是,這沒有問題。 – Luuxter

0

你可以去顯示flex,但IE的支持是相當災難性的。如果您關心瀏覽器支持(您應該),請參閱下面的示例。

<div class="list"> 
    <div class="item"> 
    <img src="https://unsplash.it/50/40" alt="">  
    </div> 
    <div class="item"> 
    <img src="https://unsplash.it/50/60" alt=""> 
    </div> 
    <div class="item"> 
    <img src="https://unsplash.it/50/30" alt=""> 
    </div> 
    <div class="item"> 
    <img src="https://unsplash.it/50" alt=""> 
    </div> 
</div> 

薩斯:

.list { 
    text-align: center; 
} 

.item { 
    position: relative; 
    display: inline-block; 
    vertical-align: top; 
    height: 5rem; 
    width: 5rem; 
    background: red; 

    img { 
    position: relative; 
    top: 50%; 
    transform: translateY(-50%); 
    } 
} 

確保添加前綴的變換屬性爲好。

小提琴:https://jsfiddle.net/k433b6up/

0

你期望的結果是不完全清楚,但這裏有兩種不同的解釋一些選項:

改變圖像的顯示性能和設置文本對齊到其容器會保持它的原生高度和寬度,而在容器中心吧:

.img-container { 
    max-height: 300px; 
    overflow: hidden; 
    text-align: center; 
} 

.img-container img { 
    display: inline-block; 
    max-height: 100%; 
    max-width: 100%; 
} 

演示:https://jsfiddle.net/5suo8tbw/

如果您嘗試使用img元素實現背景填充,則應考慮使用object-fit: cover屬性。這將始終填充容器的尺寸,保持圖像的縱橫比,並將其居中放置在容器中。

.img-container { 
    max-height: 300px; 
    overflow: hidden; 
} 

.img-container img { 
    object-fit: cover; 
    height: 100%; 
    width: 100%; 
} 

演示:https://jsfiddle.net/5suo8tbw/1/

這裏有一個鏈接到規格:https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

對於跨瀏覽器支持,檢查出的填充工具:https://github.com/anselmh/object-fit