响应图像和负边距

时间:2012-11-17 00:44:16

标签: responsive-design

我有一个网站,我有一个带填充的元素。我希望图像是容器的整个宽度,无论填充,所以我添加了一个等于填充的负边距,使其向右伸展到边缘。当我使用响应式图像时出现问题。他们忽略了负边距并压缩到容器大小加上填充。

示例:

<article style="padding:20px">
<img style="margin:0 -20px;">
</article>

在一个没有响应的世界中,这很好用。我如何通过响应式图像实现这一目标。我意识到我可以关闭并重新打开文章标签,但这会在我的实际代码中引起一堆其他问题,所以我希望有一个替代方案。

1 个答案:

答案 0 :(得分:3)

最有可能的唯一方法是将图像包装成div,例如

<article>
    <p>...</p>
    <div class="img-wrapper">
        <img src="..." />
    </div>
    <p>...</p>
</article>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

用css

article {
    padding: 20px;
}
.img-wrapper {
    margin: 0 -20px; /* minus left/right padding of article */
    text-align: center; /* center small images */
    line-height: 0; /* remove possible gap below image */
}
​​.img-wrapper > img {
    max-width: 100%; /* max-width now is relative to .img-wrapper */
    height: auto; /* to keep aspect ratio */
}​​