响应式图像和负边距 [英] Responsive images and negative margin
问题描述
我有一个网站,其中有一个带填充的元素.无论填充如何,我都希望图像是容器的全宽,因此我添加了一个等于填充的负边距,使其延伸到边缘.当我使用响应式图像时会出现问题.他们忽略负边距并压缩到容器大小加上填充.
示例:
<img style="margin:0 -20px;"></文章>
在一个无响应的世界中,这很好用.我将如何使用响应式图像实现这一目标.我意识到我可以关闭并重新打开文章标签,但这会在我的真实代码中导致一系列其他问题,所以我希望有一个替代方案.
很可能唯一的方法是将图像包装到 div 中,例如
<p>...</p><div class="img-wrapper"><img src="..."/>
<p>...</p></文章>
用css
文章{填充:20px;}.img 包装器 {边距:0 -20px;/* 减去文章的左/右填充 */文本对齐:居中;/* 居中小图像 */行高:0;/* 删除图像下方可能的间隙 */}.img-wrapper >图像{最大宽度:100%;/* 现在最大宽度是相对于 .img-wrapper */高度:自动;/* 保持纵横比 */}
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.
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 */
}
这篇关于响应式图像和负边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!