CSS – 为什么百分比高度不起作用? [英] CSS – why doesn’t percentage height work?

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

问题描述

为什么 height 的百分比值不起作用,而 width 的百分比值起作用?

例如:

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

#working{宽度:80%;高度:140px;背景:橙色;}#不工作{宽度:80%;高度:30%;背景:绿色;}

#working 的宽度最终为视口的 80%,但 #not-working 的高度最终为 0.

解决方案

块元素的高度默认为块内容的高度.所以,鉴于这样的事情:

<div id="内部"><p>煎饼屋在哪里?</p>

#inner 将变得足够高以包含该段落,而 #outer 将增长到足够高以包含 #inner.

当您将高度或宽度指定为百分比时,这是相对于元素父级的百分比.在宽度的情况下,除非另有说明,否则所有块元素都与其父元素一样宽,一直到 ;因此,块元素的宽度与其内容无关,并且说 width: 50% 会产生明确定义的像素数.

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

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.

解决方案

The height of a block element defaults to the height of the block's content. So, given something like this:

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

#inner will grow to be tall enough to contain the paragraph and #outer will grow to be tall enough to contain #inner.

When you specify the height or width as a percentage, that's a percentage with respect to the element's parent. In the case of width, all block elements are, unless specified otherwise, as wide as their parent all the way back up to <html>; so, the width of a block element is independent of its content and saying width: 50% yields a well defined number of pixels.

However, the height of a block element depends on its content unless you specify a specific height. So there is feedback between the parent and child where height is concerned and saying height: 50% doesn't yield a well defined value unless you break the feedback loop by giving the parent element a specific height.

这篇关于CSS – 为什么百分比高度不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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