【问题标题】:how to cancel left and right margin to have a 100% wide image如何取消左右边距以获得100%宽的图像
【发布时间】:2020-11-30 11:30:47
【问题描述】:
我有一个关于 CSS 的问题,
我在某个部分的页面右侧和左侧有 18px 的边距
我需要能够绕过此规则,以便图像(儿童)可以 100% 宽
如果我使用负边距它不起作用,如果我使用 100vw 它会添加一个滚动条
如何获得与页面全宽的图像?
这里是一个例子https://codepen.io/astr0cd/pen/YzqXmEp
.section {
margin: 60px 18px;
}
.image {
width: 100%;
height: 400px;
margin-left: -18px;
margin-right: -18px;
object-fit: cover;
}
<div class="section">
<img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg" alt="#" class="image">
</div>
【问题讨论】:
标签:
html
css
image
margin
【解决方案1】:
您可以使用和绝对定位。
。图片 {
位置:绝对;
...其他代码
}
【解决方案2】:
你可以像下面那样做。注意.image 类的工作方式。在这种情况下,无论.section 类有多少保证金,.image 都将是 100% width
.section{
margin: 60px 18px;
}
.image {
width: 100vw;
position: relative;
left: 50%;
right: 50%;
margin-left: -50vw;
margin-right: -50vw;
}
<div class="section">
<img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg" alt="#" class="image">
</div>
【解决方案3】:
删除margin-right: -18px 并将宽度更改为calc(100% + 36px)。此外,您应该将margin:0 设置为body,而不是html。
body {
margin: 0;
padding: 0;
}
.section {
margin: 60px 18px;
}
.image {
width: calc(100% + 36px);
height: 400px;
margin-left: -18px;
object-fit: cover;
}
<section class="section">
<img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg" alt="#" class="image">
</section>