Gabriel R
Gabriel R

Reputation: 107

Best solution to remove horizontal scrollbar with img width of 100vw?

Setting the width of an <img> to 100vw causes a horizontal scrollbar to appear on the bottom of the viewport, and the only working solution I have found to get rid of the latter is to use overflow-y: overlay;. However, I have read that this solution isn't optimal. What's a better alternative?

body {
  margin: 0;
  overflow-y: overlay;
}

Upvotes: 1

Views: 2878

Answers (3)

Vinod Bokde
Vinod Bokde

Reputation: 338

The horizontal scroll had come up because this is only an issue on windows. On Mac or Android the scrollbars are placed on top of the content and disappear once you're done scrolling so they don't affect the view width.

If max-width: 100% is the width of the viewport without scrollbars, then you didn't need 100vw in the first place.

You could just have use width: 100% because the element doesn't have any positioned ancestor, so its reference is the body.

A simple solution in your case is by giving max-width: 100%.

HTML would be like:

<div class="box">
    .
    .
    .
</div>

Use this CSS:

html, body {
    margin: 0;
    padding: 0
}
    .box {
        width: 100vw;
        max-width:100%; // This is very Important.
        height: 100vh;
    }

Upvotes: 3

adel
adel

Reputation: 3507

add:

div{
  width:100vw;
  height:100vh;
  background-color:blue;
}
*{
  margin:0;
  padding:0;
}
<div></div>

this will remove default margin and padding

Upvotes: -1

Madan Bhandari
Madan Bhandari

Reputation: 2184

Scrollbars are included in the vw and vh so the scroll will be added to allow you to see beyond viewport. You can set max-width: 100% to remove scrollbar.

width: 100vw;
max-width :100%

Upvotes: 3

Related Questions