Html 宽度:100% 和宽度:100vw 之间的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25225682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:28:21  来源:igfitidea点击:

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

htmlcss

提问by alokrajiv

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.

我必须适应屏幕高度的 iframe。显然,我想要 100% 的宽度,但由于这不起作用,我使用了 100vh。但是像 vw 一样的 vh 并不完全是 100%。在我的笔记本电脑中通过 chrome 虽然 100% 宽度完美呈现而无需水平滚动条,vw 有大约一厘米的额外。

回答by Havenard

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

vw 和 vh 分别代表视口宽度和视口高度。

The difference between using width: 100vwinstead 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.

使用width: 100vw而不是的区别在于width: 100%,虽然100%会使元素适合所有可用空间,但视口宽度有一个特定的度量,在这种情况下,可用屏幕的宽度,包括文档边距

If you set the style body { margin: 0 }, 100vw should behave the same as 100%.

如果您设置 style body { margin: 0 },则 100vw 的行为应与 100% 相同。

Additional notes

Using vwas 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 properly in both workstation and mobile.

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

补充说明

vw网站中的所有内容(包括字体大小和高度)用作单位,将使网站始终与设备的屏幕宽度成比例地显示,无论其分辨率如何。这使得确保您的网站在工作站和移动设备中正确显示变得非常容易。

您可以font-size: 1vwbodyCSS 中设置(或任何适合您项目的大小),并且以rem单位指定的所有内容都将根据设备屏幕自动缩放,因此很容易将现有项目甚至框架(例如 Bootstrap)移植到此概念。

回答by James Filby

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vwfor width: 100%to get rid of the horizontal scrollbar.

Havengard 的回答似乎并不完全正确。我发现 vw 填充了视口宽度,但没有考虑滚动条。因此,如果您的内容比视口高(因此您的网站有一个垂直滚动条),那么使用 vw 会产生一个小的水平滚动条。我不得不转出width: 100vwwidth: 100%摆脱水平滚动条。