2016-06-29 28 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>