如何使div的浏览器窗口高度为100% [英] How to make a div 100% height of the browser window
问题描述
我有一个包含两列的布局-左边的div
和右边的div
.
I have a layout with two columns - a left div
and a right div
.
右侧的div
具有灰色的background-color
,我需要根据用户浏览器窗口的高度将其垂直扩展.现在,background-color
终止于该div
中的最后一条内容.
The right div
has a grey background-color
, and I need it to expand vertically depending on the height of the user's browser window. Right now the background-color
ends at the last piece of content in that div
.
我尝试过height:100%
,min-height:100%;
等
推荐答案
有两个CSS 3测量单位,称为:
There are a couple of CSS 3 measurement units called:
从上面链接的W3候选推荐书中:
From the linked W3 Candidate Recommendation above:
视口百分比长度相对于初始包含块的大小.更改初始包含块的高度或宽度时,将对其进行相应缩放.
这些单位是vh
(视口高度),vw
(视口宽度),vmin
(视口最小长度)和vmax
(视口最大长度).
These units are vh
(viewport height), vw
(viewport width), vmin
(viewport minimum length) and vmax
(viewport maximum length).
对于这个问题,我们可以使用vh
:1vh
等于视口高度的1%.也就是说,100vh
等于浏览器窗口的高度,而不管元素在DOM树中的位置:
For this question, we can make use of vh
: 1vh
is equal to 1% of the viewport's height. That is to say, 100vh
is equal to the height of the browser window, regardless of where the element is situated in the DOM tree:
<div></div>
CSS
div {
height: 100vh;
}
这实际上就是所需要的.这是正在使用的 JSFiddle示例 .
This is literally all that's needed. Here is a JSFiddle example of this in use.
除Opera Mini之外,所有最新的主流浏览器目前都支持此功能.查看我可以使用... 以获得进一步的支持.
This is currently supported on all up-to-date major browsers apart from Opera Mini. Check out Can I use... for further support.
对于具有左右分隔线的当前问题,这里是 JSFiddle示例,其中显示了同时包含vh
和vw
的两列布局.
In the case of the question at hand, featuring a left and a right divider, here is a JSFiddle example showing a two-column layout involving both vh
and vw
.
以这种布局为例:
<body style="height:100%">
<div style="height:200px">
<p style="height:100%; display:block;">Hello, world!</p>
</div>
</body>
此处的p
标签设置为100%的高度,但是由于其包含的div
具有200像素的高度,因此200像素的100%变为200像素,不是 body
高度.相反,使用100vh
意味着p
标记将是body
的100%高度,而与div
高度无关.看看这个伴随JSFiddle的,可以轻松地看到其中的区别!
The p
tag here is set to 100% height, but because its containing div
has 200 pixels height, 100% of 200 pixels becomes 200 pixels, not 100% of the body
height. Using 100vh
instead means that the p
tag will be 100% height of the body
regardless of the div
height. Take a look at this accompanying JSFiddle to easily see the difference!
这篇关于如何使div的浏览器窗口高度为100%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!