绝对元素的百分比值是指浏览器的宽度和高度吗? [英] percentage values for absolute elements refers to browser width and height?

查看:25
本文介绍了绝对元素的百分比值是指浏览器的宽度和高度吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,当使用 css 百分比作为相对元素的属性值时,该元素会检查其父元素的值并根据该父元素的大小调整大小.

绝对元素的场景是什么?我正在浏览一个 css 文件,我发现了这个:

html {边距:0;填充:0;高度:100%;宽度:100%;溢出-x:隐藏;}

在绝对元素上设置百分比以获取其浏览器宽度和高度是否可以?

解决方案

当元素具有 position:absolute 时,widthheight百分比是根据整个浏览器尺寸计算的.

见下面的代码:

<头><风格>#一种 {位置:绝对;宽度:50%;}</风格><body onload="alert(document.getElementById('a').offsetWidth);"><div style="width:200px;"><div id="a">你好</div>

</html>

即使父 div 的宽度只有 200px,元素显示浏览器宽度的一半.

一旦我将其更改为 position:relative;,警报将显示 100.

As far as I know, when using css percentage for properties value for an relative element, this element checks the value of its parent and adjust the size based on this parent size.

What is the scenario for absolute elements? I was looking through a css file and I found this:

html {
    margin: 0;
    padding: 0;
    height: 100%;
    width: 100%;
    overflow-x: hidden;
}

Is this ok to have percentage on absolute elements to get its browser width and height?

解决方案

When an element has position:absolute, the width and height percentages are calculated based on the whole browser dimensions.

See below code:

<html>
    <head>
        <style>
            #a {
                position: absolute;
                width:50%;
            }
        </style>

    </head>
    <body onload="alert(document.getElementById('a').offsetWidth);">
        <div style="width:200px;">
            <div id="a">Hello</div>
        </div>
    </body>
</html>

Even though the width of parent div is only 200px, the element displays half of the browser width.

Once I change it to position:relative;, the alert will say 100.

这篇关于绝对元素的百分比值是指浏览器的宽度和高度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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