我对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>
答案 0 :(得分:2)
删除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>
答案 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>
答案 2 :(得分:-1)
您可以使用和绝对定位。 。图片 { 位置:绝对; ...其他代码 }