【问题标题】:Responsive images and negative margin响应式图像和负边距
【发布时间】:2012-11-05 18:17:26
【问题描述】:

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

例子:

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

在无响应的世界中,这可以正常工作。我将如何使用响应式图像来实现这一点。我意识到我可以关闭并重新打开文章标签,但这会在我的真实代码中引起一堆其他问题,所以我希望有一个替代方案。

【问题讨论】:

    标签: responsive-design


    【解决方案1】:

    很可能唯一的方法是将图像包装到一个 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 */
    }​​
    

    【讨论】:

    • 我正要问一个与 OP 非常相似的问题,但“可能已经有你答案的问题”列表将我指向这里,这正是我所需要的。谢谢你:)
    猜你喜欢
    • 2014-01-25
    • 2011-08-10
    • 1970-01-01
    • 2011-05-12
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多