Responsive images and negative margin

孤街醉人 提交于 2019-12-11 23:23:40

问题


I have a site where I have an element with padding. I want the images to be the full width of the container regardless of padding, so I have added a negative margin equal to the padding to make it stretch right to the edge. The problem arises when I use responsive images. They ignore the negative margin and squish down to the container size plus padding.

Example:

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

In a non-responsive world this works fine. How would I achieve this with responsive images. I realize I could close and re-open the article tag, but this will cause a bunch of other issue in my real code, so I'm hoping for an alternative.


回答1:


Most likely the only way is to wrap images into a div, e.g.

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

with 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 */
}​​


来源:https://stackoverflow.com/questions/13426478/responsive-images-and-negative-margin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!