Html 高度百分比在 CSS 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16642866/
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 08:34:14  来源:igfitidea点击:

Height percentage not working in CSS

htmlcssheight

提问by Flezcano

I am trying to use height property using percentages, but it doesn't work. I want to use percentage so it looks fine in any resolution.

我正在尝试使用百分比来使用高度属性,但它不起作用。我想使用百分比,以便在任何分辨率下看起来都很好。

<div id="bloque_1" style="height: 80%;background: red">   
</div>

How can I make it work?

我怎样才能让它工作?

回答by Mr. Alien

When you are using %for width, or height, the 1st question you should ask is that 80%of what? So you also need to apply height to the parent element, so assuming that this element of yours is inside the body tag, you need to use this in your CSS

当您使用%宽度或高度时,您应该问的第一个问题是80%什么?所以你还需要对父元素应用高度,所以假设你的这个元素在 body 标签内,你需要在你的 CSS 中使用它

html, body {
   height: 100%;
}

So now your divelement will be 80%of 100%

所以,现在你的div元素是80%100%

Demo

演示

Side Note: Also when you are dealing with absolutepositioned elements, you may come across a scenario where your divwon't exceed the current viewport height, so in that case you need to have min-height

旁注:此外,当您处理absolute定位元素时,您可能会遇到div不会超过当前视口高度的情况,因此在这种情况下,您需要有min-height

回答by neokio

Everything outside of bloque_1will need a height as well, or you'll get 80% of 0. You may also have to apply a height of 100% to the body.

外面的所有东西bloque_1也需要一个高度,否则你会得到 0 的 80%。你可能还需要将 100% 的高度应用到body.

Here's a jsfiddlethat shows it in action.

这是一个jsfiddle,它显示了它的实际效果。

回答by swapnesh

Apply 100%height on your parent element

100%在父元素上应用高度

HTMLcode-

HTML代码-

<html>
<body>
<div id="bloque_1" style="height:80%;background:red;width:100%;">   
</div>
</body>
</html>  

CSSPart-

CSS部分-

html, body { height: 100%; width: 100%; margin: 0;background: #3c3c3c }

Working Fiddle - http://jsfiddle.net/SEafD/1/

工作小提琴 - http://jsfiddle.net/SEafD/1/

回答by Rajender Joshi

Demo

演示

html,body{
    height:100%
}
#bloque_1{
    background:red;
    height:80%;
}