Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

percentage values for absolute elements refers to browser width and height?

Tags:

html

css

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?

like image 362
Guilherme Longo Avatar asked Feb 17 '26 08:02

Guilherme Longo


1 Answers

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.

like image 141
ATOzTOA Avatar answered Feb 19 '26 21:02

ATOzTOA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!