2

I've Written that code and it was showing me a scrollbar on x-axis.

 nav{width:100vw;}

but when i switch the values from vw to % its just starts working fine.

then why is there a scroll with vw?

  • For desktops, the browser window is wider than the viewport (adding the scrollbar width), so if you set the width to `100vw` for the element, it will go outside the html. – s.kuznetsov Aug 25 '20 at 17:59
  • There must be some `margin` or `padding` applied to the same element. You can get rid of this issue in two ways. 1) Highly recommended. apply `box-sizing: border-box` property to the `body` element. 2) Simple hack apply width by subtracting the total of `margin` and `padding` values. eg. if horizontal margin is 5px each side, and horizontal padding 5px each side. nav { width: calc(100vw - 20px); } – Sunny Vaghadia Aug 25 '20 at 18:07
  • Use `box-sizing: border-box;` to avoid problems of increasing the width of an element by padding or borders. Be careful with adding a horizontal margin becaus this will always be added to the width of an element. – bron Aug 25 '20 at 18:12

2 Answers2

3

Because setting width to 100vw will give 100vw width to the element + any padding or margins which results in overflow

100vw element = 100vw width + padding + margin

which is not the case with 100%;

100% element = 100% width inclusve of margin + padding

Mostly the reason is body margin. So set body -> margin to 0 and see it working as 100%.

Ajeet Eppakayala
  • 1,186
  • 1
  • 10
  • 17
  • Horizontal margin, padding and borders are added to the widht of an element. By using `box-sizing: border-box`, only the horizontal margin is added to the width – bron Aug 25 '20 at 18:18
2

% is relative to the parent element. So 100% will take the 100% area of the parent element.

But vw is relative to the viewport directly. Viewport is the visible area of a web page. 100vw is taking the entire viewport width available.

You can check this article for example.

proshi
  • 91
  • 3