Search code examples
htmlcss

Difference between Width:100% and width:100vw?


I have to fit an iframe in screen height. Obviously, I wanted 100% as in width but, since that doesn't work, I used 100vh. But vh like vw is not exactly 100%. In my laptop through chrome while the 100% width renders perfectly without the need for a horizontal scroll bar, vw has about a centimeter extra.


Solution

  • vw and vh stand for viewport width and viewport height respectively.

    The difference between using width: 100vw instead of width: 100% is that while 100% will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.

    If you set the style body { margin: 0 }, 100vw should behave the same as 100% (for an element that is a child to body).

    Additional notes

    Using vw as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed exactly the same in both workstation and mobile.

    You can set font-size: 1vw (or whatever size suits your project) in your body CSS and everything specified in rem units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap that already uses rem as unit for everything) to this concept.