How to remove horizontal scrolling when the image is on the right

Viewed 31

In this example, the image is superimposed on the container block via :: before with negative left: -80px. And here you are good, i.e. no scrolling up to width: 300px.

But, if you do instead of left: -80px; -> right: -80px; so that the overlay is calculated relative to the right corner of the container. And horizontal scrolling appears already at width less than 492px;

How to remove scrolling for the right option? (i.e. do as in the left one). Without (overflow: hidden)

* {
  margin: 0;
  padding: 0;
}
div {
  margin: 100px auto;
  border: 1px solid gray;
  width: 500px;
  position: relative;
}
.bg-img::before {
  content: "";
  position: absolute;
  width: 160px;
  height: 110px;
  z-index: -1;
  top: -50px;
  left: -80px; /* is ok */
  /* right: -80 */ /* bad */
  background-image: url(https://i.ibb.co/Qdz79gF/Sample.png);
  background-size: 100% 100%;
}
<div class="bg-img">
  This is some text<br>
  This is some text<br>
  This is some text<br>
  This is some text<br>
  This is some text
</div>

1 Answers

In both cases your content is wider than the screen. But when the web page uses the LTR direction and the block goes off the left edge of the screen, the browser doesn't add horizontal scrolling.

To solve the problem on the right side, you can wrap your content with an extra block that has the overflow-x: hidden; property. You can also apply this property directly to the body tag, but I prefer to use an additional wrapper block for a section or for an entire page.

I've also replaced width: 500px; by max-width: 500px; to make this block more responsive.

* {
  margin: 0;
  padding: 0;
}
.wrapper {
  overflow-x: hidden;
}
.bg-img {
  margin: 100px auto;
  border: 1px solid gray;
  max-width: 500px;
  position: relative;
}
.bg-img::before {
  content: "";
  position: absolute;
  width: 160px;
  height: 110px;
  z-index: -1;
  top: -50px;
  right: -80px;
  background-image: url(https://i.ibb.co/Qdz79gF/Sample.png);
  background-size: 100% 100%;
}
<div class="wrapper">
  <div class="bg-img">
    This is some text<br>
    This is some text<br>
    This is some text<br>
    This is some text<br>
    This is some text
  </div>
</div>

Related