如何取消左右边距以获得100%宽的图像

时间:2020-08-10 20:11:06

标签: html css image margin

我对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>

3 个答案:

答案 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)

您可以使用和绝对定位。 。图片 { 位置:绝对; ...其他代码 }