Search code examples
htmlcssalignmentvertical-alignment

How to align div to parent div?


suppose we have 4 dives. the first div is outer div. i want to create a HTML that the second div size be 50% first and be in middle bottom of first div. the third div size be 50% second and be in middle left of second div. the fourth div size be 50% third div and be in middle top of third div.

how can i do it?

enter image description here


Solution

  • Is this your desired output? It’s made using position, top and bottom, and translate to make sure it’s centered right.

    .div1 div { /* makes every small div 50% the size of the previous */
        width: 50%;
        height: 50%;
    }
    .div1 {
        width: 200px;
        height: 200px;
        background-color: red;
    }
    .div2 {
        background-color: green;
        position: relative;
        top: 100%;
        left: 50%;
        transform: translate(-50%, -100%);
    }
    .div3 {
        background-color: pink;
        position: relative;
        top: 50%;
        transform: translate(0, -50%);
    }
    .div4 {
        background-color: lightblue;
        position: relative;
        left: 50%;
        transform: translate(-50%, 0);
    }
    <div class="div1">
        <div class="div2">
            <div class="div3">
                <div class="div4">
                    
                </div>
            </div>
        </div>
    </div>