loading...
Cover image for Why 100vw causes horizontal scrollbar

Why 100vw causes horizontal scrollbar

tepythai profile image Tepy Thai ・2 min read

This post is from my personal blog here

Do you ever wonder why sometimes your site just has a horizontal scrollbar appeared out of nowhere? Today I just ran into it again (as always 😆) and I somehow figured out how to remove it. So here is the step I took to debug and fix it.

  • Try the global border or outline color trick to find which element is causing it:
* {
  border: 1px solid red;
}
  • Find elements with width bigger than the document's width (more from csstrick)
var docWidth = document.documentElement.offsetWidth;

[].forEach.call(document.querySelectorAll('*'), function (el) {
  if (el.offsetWidth > docWidth) {
    console.log(el);
  }
});
  • Most of the times, I always find the 100vw value on the width that is the cause of the overflow. So, if that is the case, you can try replacing it with width: 100% instead and see if it works. Try with its inner elements as well if present.

So, back to the title, why would 100vw be the cause? Well, the answer is:

When you set an element's width to 100vw, the element's width now will be the whole view width of the browser and the important part is 100vw does not include the vertical scrollbar's width into its calculation at all. Therefore, when there is a vertical scrollbar, the total width will be the sum of the element's width and the vertical scrollbar's width, which causes the overflow on the x-axis and thus the horizontal scrollbar.

Hope this helps!

Feel free to correct me if you think there is something wrong 😃

Posted on Jun 5 by:

tepythai profile

Tepy Thai

@tepythai

Frontend Developer - React - Next - Gatsby - Graphql - Styled-Components - Tailwindscss

Discussion

markdown guide
 

Most of the time I see juniors creating a section in a one-pager with 100vh and 100vw, 100vh from my part is understandable, if they don't want/or know how to setup html, body height. But if the element is already in a 100% container, and it doesn't need to overflow from a smaller container to achieve the 100% width, then why would anyone use 100vw? Especially if I need to style something I wouldn't make it render badly without js. Don't get me wrong I see that you recommend using 100%, just 100vw can make me really upset, thanks for the article :)

 

Yeah, I would want to avoid the 100vw within a 100% container as well. Mostly I only use 100% for inner elements unless I really want the width to be relative to the viewport, then I would use 100vh. Anyway, thanks for the clarification :)

 

Has anyone tried using 100vw with the below?

box-sizing: border-box;
 

I've never tried using it with box-sizing before, but I don't think box-sizing has anything to do with this case at all.