2016-06-29 29 views
2

如何確保容器內的img能夠集中並正確地從移動設備擴展到桌面?這是一個demo on Codepen。縮放到移動,以便更好地理解問題用響應<img>填充div並集中位置

HTML

<div class="image-container"> 
    <img src="https://placeimg.com/470/310/people" alt="" /> 
</div> 

CSS

.image-container{ 
width: 100%; 
height: 500px; 
max-height: 500px; 
background: red; 
overflow: hidden; 
text-align: center; 
position: relative; 
display: block; 
} 

img{ 
height: auto; 
width: 100%; 
max-width: 100%; 
position: absolute; 
top: -50%; 
left: 0; 
} 

我問這個,因爲像失去了它的高度上移動,看起來不正確。我有點像這樣工作,像`background-size:cover。我想要圖像完全填充容器

回答

0

要將圖像水平和垂直居中放置div,您可以設置top: 50%left: 50%,然後只需添加transform: translate(-50%, -50%)

要使圖像響應,您可以使用max-width: 100%,默認情況下,高度爲自動。

.image-container { 
 
    width: 100%; 
 
    height: 500px; 
 
    background: red; 
 
    overflow: hidden; 
 
    position: relative; 
 
} 
 
img { 
 
    max-width: 100%; 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 50%; 
 
    transform: translate(-50%, -50%); 
 
}
<div class="image-container"> 
 
    <img src="https://placeimg.com/470/310/people" alt="" /> 
 
</div>

另一種選擇是使用Flexbox如果你不想使用relative/absolute位置,但保持的img響應,您可以使用object-fit: containheight: 100%

.image-container { 
 
    width: 100%; 
 
    height: 500px; 
 
    background: red; 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
} 
 

 
img { 
 
    max-width: 100%; 
 
    object-fit: contain; 
 
}
<div class="image-container"> 
 
    <img src="https://placeimg.com/470/310/people" alt="" /> 
 
</div>

如果你想img表現得像background-size: cover一個辦法就是使用object-fit: coverheight: 100%width: 100%

body, 
 
html { 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 
.image-container { 
 
    width: 100%; 
 
    height: 500px; 
 
    background: red; 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
} 
 
img { 
 
    width: 100%; 
 
    height: 100%; 
 
    object-fit: cover; 
 
}
<div class="image-container"> 
 
    <img src="https://placeimg.com/470/310/people" alt="" /> 
 
</div>

+0

說實話,我是相當新了flexbox。我在波旁網格中使用了你的代碼,但它不起作用。 – samsos

0

您可以添加margin:0 auto;水平對齊中心。 Remove width:100%,因爲這會拉伸圖像的寬度,除非您想要。保留height:autowidth進行調整。

.image-container{ 
 
    width: 100%; 
 
    height: 500px; 
 
    max-height: 500px; 
 
    background: red; 
 
    overflow: hidden; 
 
    text-align: center; 
 
    position: relative; 
 
    display: block; 
 
} 
 

 
img{ 
 
height: auto; 
 
max-width: 100%; 
 
margin:0 auto; 
 
}
<div class="image-container"> 
 
    <img src="https://placeimg.com/470/310/people" alt="" /> 
 
</div>