2009-10-25 154 views
115

我试图将<div>设置为CSS中的某个百分比高度,但它只是保持与其中的内容大小相同。但是,当我删除HTML 5 <!DOCTYTPE html>时,它会起作用,<div>会根据需要占据整个页面。我想要页面验证,那么我该怎么办?百分比高度HTML 5/CSS

我对这个<div> CSS,其中有page的ID:

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

这里的CSS'用百分比值height'财产的一个简单而明确的解释:http://stackoverflow.com/a/31728799/3597276 –

+0

解决DOCTYPE问题:http://stackoverflow.com/ a/32215263/3597276 –

回答

295

我想一个div设置一定比例的高度在CSS

的百分比是多少?

设置一个百分比高度,它的父元素(*)必须有一个明确的高度。这是相当不言而喻的,因为如果你将高度保留为auto,该块将占据其内容的高度......但是如果内容本身具有以父母的百分比表示的高度,小捕捉22.浏览器放弃,只是使用内容的高度。

所以div的父母必须有明确的height财产。虽然这个高度也可以是一个百分比,如果你想,这只是将问题提升到一个新的水平。

如果你想在div高度视口高度的百分比,股利的每一个祖先,包括<html><body>,必须有height: 100%,所以有明确的百分比高度的环比回落到div。

(*:或者,如果在div被定位时,“包含块”,这是最近的祖先还可以定位)

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

div { 
    height:100vh; 
} 

在这里看到more info

+0

虽然不适用于纵向屏幕方向http://stackoverflow.com/questions/23198237/percentage-of-height-not-working-for-portrait-screen-orientation – Dchris

+0

请参阅下面的布赖恩坎贝尔的答案我相信这是正确的解决方案。这个答案似乎是一个解决方法,并没有解决实际问题。 –

59

您需要设置的高度上<html><body>元素为好;否则,它们只会大到足以容纳内容。 For example

<!DOCTYPE html> 
 
<title>Example of 100% width and height</title> 
 
<style> 
 
html, body { height: 100%; margin: 0; } 
 
div { height: 100%; width: 100%; background: red; } 
 
</style> 
 
<div></div>

+5

¬_¬我花了20分钟才弄清楚我必须将文档高度设置为100%。我读这篇文章有点太晚了,但它仍然非常出色。 *叹息* – omninonsense

+0

这应该被视为答案,因为它给很多来这里的人提供了一个解决方案,想知道怎么做才能看到第一个答案,并且认为它不可能,并且不用考虑是否存在任何其他方法 –

+0

我同意这是正确的答案,高度不起作用,因为父元素是body和html需要设置。这个答案应该是被接受的答案。 –

12

bobince的回答会让你知道在哪些情况下“身高:XX%;”将或不会工作。

如果您想创建一个具有设定比例(高度:自身宽度的百分比)的元素,最好的方法是使用padding-bottom有效地设置高度。例如,对于方形:

<div class="square-container"> 
    <div class="square-content"> 
    <!-- put your content in here --> 
    </div> 
</div> 

.square-container { /* any display: block; element */ 
    position: relative; 
    height: 0; 
    padding-bottom: 100%; /* of parent width */ 
} 
.square-content { 
    position: absolute; 
    left: 0; 
    top: 0; 
    height: 100%; 
    width: 100%; 
} 

方形容器将刚制成的填充物,并且内容将扩大到填充容器。关于这个问题的2009年以来的长文章:http://alistapart.com/article/creating-intrinsic-ratios-for-video

+0

非常感谢! – zaw

3

您可以使用100vw/100vh。 CSS3为我们提供了视口相关单位。100vw意味着100%的视口宽度。 100vh;身高的100%。

<div style="display:flex; justify-content: space-between;background-color: lightyellow; width:100%; height:85vh"> 
     <div style="width:70%; height: 100%; border: 2px dashed red"></div> 
     <div style="width:30%; height: 100%; border: 2px dashed red"></div> 
    </div>