css calculate element percentage size

Include block definition:

Poke the guest here~

The percentage is based on the width of the containing block

First, children set the position as absolute positioning, and the parent element as relative or absolute or fixed; then the percentage size of children is calculated based on the width of parent (including blocks for children), and the width and length.

css:

   .parent{
            position: relative;
            width: 400px;
            height: 400px;
        }
        .children{
            position: absolute;
            width: 200px;
            height: 200px;
            background:red;
            padding-top: 20%;
        }

html:

<div class="parent">
    <div class="children"></div>
</div>

Second, the position of parent is the default static, and the position of children is set to absolute; then the percentage size of children is calculated based on the width of the viewport. The position of all ancestor elements of children is the default

css:

   .parent{
            width: 400px;
            height: 400px;
        }
        .children{
            position: absolute;
            width: 200px;
            height: 200px;
            background:red;
            padding-top: 20%;
        }

html:

<div class="parent">
    <div class="children"></div>
</div>

Third, set children's position to relative, then the percentage size of children is calculated based on the width of the nearest block container (equivalent to block element; block, inline block, list item, table)

css:

   .parent{
            width: 400px;
            height: 400px;
        }
        .children{
            position: relative;
            width: 200px;
            height: 200px;
            background:red;
            padding-top: 20%;
        }

html:

<div class="parent">
    <div class="children"></div>
</div>

Fourth: if children's position is set to fixed, the percentage size of children is calculated based on the width of the viewport

css:

   .parent{
            position:relative;
            width: 400px;
            height: 400px;
        }
        .children{
            position: fixed;
            width: 200px;
            height: 200px;
            background:red;
            padding-top: 20%;
        }

html:

<div class="parent">
    <div class="children"></div>
</div>

Posted on Tue, 31 Mar 2020 16:19:30 -0700 by mirana