maxime rochant
maxime rochant

Reputation: 1

how to cancel left and right margin to have a 100% wide image

i have an question about css,

I have a margin which is 18px on the right and on the left of the page on a section I need to be able to bypass this rule so that an image (a child) can be 100% wide

if i use negative marging it doesn't work, if i use 100vw it adds a scroll bar

how do i get an image that is the full width of the page?

here an example 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>

Upvotes: 0

Views: 568

Answers (3)

Yhuakim
Yhuakim

Reputation: 1

You can use and absolute positioning. .image { position: absolute; ...other codes }

Upvotes: -2

Evik Ghazarian
Evik Ghazarian

Reputation: 1791

You can do it like below. Pay attention to how .image class works. In this case no matter how much margin .section class have the .image will be at 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>

Upvotes: 2

doğukan
doğukan

Reputation: 27431

Remove the margin-right: -18px and change the width as calc(100% + 36px). Also you should set the margin:0 to body, not to 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>

Upvotes: 2

Related Questions