CSS –为什么身高百分比不起作用?\[重复\]

css CSS

小小Gil

2020-03-26

How come a percentage value for height doesn’t work but a percentage value for width does?

For example:

<div id="working"></div>
<div id="not-working"></div>
#working{
    width:80%;
    height:140px;
    background:orange;
}
#not-working{
    width:80%;
    height:30%;
    background:green;
}

The width of #working ends up being 80% of the viewport, but the height of #not-working ends up being 0.

第3771篇《CSS –为什么身高百分比不起作用?\[重复\]》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
卡卡西Near 2020.03.26

另一种选择是向div添加样式

<div style="position: absolute; height:somePercentage%; overflow:auto(or other overflow value)">
 //to be scrolled 
</div>

这意味着元素相对于最近定位的祖先进行了定位。

卡卡西Near 2020.03.26

我认为您只需要给它一个父容器即可,即使该容器的高度以百分比定义。这可以正常工作:JSFiddle

html, body { 
    margin: 0; 
    padding: 0; 
    width: 100%; 
    height: 100%;
}
.wrapper { 
    width: 100%; 
    height: 100%; 
}
.container { 
    width: 100%; 
    height: 50%; 
}
阿飞 2020.03.26

没有内容,身高就没有价值可计算百分比。但是,如果未指定父级,则宽度将从DOM中获取百分比。(使用您的示例)将第二个div放在第一个div内,将呈现结果...下面的示例...

<div id="working">
  <div id="not-working"></div>
</div>

第二个div将是第一个div高度的30%。

达蒙 2020.03.26

您需要给它一个高的容器。width使用视口作为默认宽度

JinJin 2020.03.26

块元素的高度默认为块内容的高度。因此,给定这样的东西:

<div id="outer">
    <div id="inner">
        <p>Where is pancakes house?</p>
    </div>
</div>

#inner将生长到足以容纳段落的高度,并且#outer将生长到足以容纳段落的高度#inner

当您将高度或宽度指定为百分比时,这是相对于元素父级的百分比。就宽度而言,除非另有说明,否则所有块元素的宽度一直与其父元素一样,一直到<html>因此,块元素的宽度与其内容无关,也就是说,它width: 50%产生了定义良好的像素数。

但是,除非您指定特定的高度,否则块元素的高度取决于其内容因此,在涉及高度的父级和子级之间会有反馈,并且height: 50%除非您通过给父元素指定特定的高度来打破反馈循环,否则不会产生明确定义的值。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android