百分比高度 HTML 5/CSS [英] Percentage Height HTML 5/CSS

查看:30
本文介绍了百分比高度 HTML 5/CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 CSS 中将

设置为某个百分比高度,但它只是保持与其中内容相同的大小.然而,当我删除 HTML 5 <!DOCTYTPE html> 时,它可以工作,<div> 根据需要占据整个页面.我想让页面通过验证,我该怎么做?

我在

上有这个 CSS,它的 ID 为 page:

#page {填充:10px;背景颜色:白色;高度:90%!重要;}

解决方案

我试图在 CSS 中将 div 设置为某个百分比高度

什么百分比?

要设置百分比高度,其父元素(*) 必须具有明确的高度.这是不言而喻的,因为如果您将高度保留为 auto,则块将采用其内容的高度……但是如果内容本身具有以百分比表示的高度父母你让自己有点 Catch 22.浏览器放弃,只使用内容高度.

所以 div 的父级必须有一个显式的 height 属性.虽然如果您愿意,该高度也可以是百分比,但这只会将问题提升到一个新的水平.

如果你想让 div 高度占视口高度的百分比,div 的每个祖先,包括 ,都有有 height: 100%,所以有一个明确的百分比高度链到 div.

(*: 或者,如果 div 已定位,则为包含块",它也是要定位的最近的祖先.)

或者,所有现代浏览器和 IE>=9 都支持相对于视口高度 (vh) 和视口宽度 (vw) 的新 CSS 单位:

div {高度:100vh;}

请参阅此处了解更多信息.

I am trying to set a <div> to a certain percentage height in CSS, but it just remains the same size as the content inside it. When I remove the HTML 5 <!DOCTYTPE html> however, it works, the <div> taking up the whole page as desired. I want the page to validate, so what should I do?

I have this CSS on the <div>, which has an ID of page:

#page {
    padding: 10px;
    background-color: white;
    height: 90% !important;
}

解决方案

I am trying to set a div to a certain percentage height in CSS

Percentage of what?

To set a percentage height, its parent element(*) must have an explicit height. This is fairly self-evident, in that if you leave height as auto, the block will take the height of its content... but if the content itself has a height expressed in terms of percentage of the parent you've made yourself a little Catch 22. The browser gives up and just uses the content height.

So the parent of the div must have an explicit height property. Whilst that height can also be a percentage if you want, that just moves the problem up to the next level.

If you want to make the div height a percentage of the viewport height, every ancestor of the div, including <html> and <body>, have to have height: 100%, so there is a chain of explicit percentage heights down to the div.

(*: or, if the div is positioned, the ‘containing block’, which is the nearest ancestor to also be positioned.)

Alternatively, all modern browsers and IE>=9 support new CSS units relative to viewport height (vh) and viewport width (vw):

div {
    height:100vh; 
}

See here for more info.

这篇关于百分比高度 HTML 5/CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆