Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with 100vw including scrollbar width

I have a div that needs to be full screen width inside a parent div that has a limited with. Simplified, it's something like:

HTML:

<div class="container">
  <div class="banner">
  </div>
</div>

CSS:

.container {
  width: 1170px;
  margin: auto;
}
.banner {
  width: 100vw;
  margin-left: calc( 50% - 50vw);
}

which works fine, except for one thing: The scrollbar on the page covers some of the content in the child div, because 100vw appearantly includes the scrollbar width. So is there a way around this so I can set the width to (100vw - scrollbar width), or perhaps a completely different way to achieve what I want to do with pure CSS?

like image 918
ReddaJoppe Avatar asked Nov 02 '25 13:11

ReddaJoppe


2 Answers

You could set the scrollbar width and subtract it from the container's width using 'pure CSS'.

You could give width to the scroll bar in webkit-browsers using:

body::-webkit-scrollbar {
 width: scrollbarwidthpx;
}

and set the content width as:

width: calc(100vw - scrollbarwidthpx);

You could make use of this article regarding customizing scrollbar

like image 61
Vishnu Avatar answered Nov 04 '25 04:11

Vishnu


Try to use % where you can. vw is a percent of the viewport width including the scrollbar while % is a percent of the wrapper object which does not get confused by the scrollbar.

In general:

  • Don't use a fixed width (px) container. It's bad practice and will not render well on mobile screens. See Responsive Web Design for more.
  • Don't use vw for containers (or banners). It has weird effects on the scrollbar.
like image 35
RWDJ Avatar answered Nov 04 '25 02:11

RWDJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!