0

I was trying to make an interface for a clock, and one of the buttons needs to be positioned at the bottom of its container div. This is the code I used:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Absolute Positioning Problem</title>
    <style>
        * {
            margin: 0px;
            padding: 0px;
        }


        #container {
            margin: auto;
            margin-top: 10px;
            width: 90%;
            aspect-ratio: 2 / 1;
            background-color: green;
            display: flex;
        }

        #blueBox {
            width: 50%;
            height: 100%;
            background-color: blue;
            position: relative;
            left: 0px;
            top: 0px;
        }

        #redBox {
            width: 50%;
            height: 100%;
            background-color: red;
            position: relative;
            right: 0px;
            top: 0px;
        }

        #topBox {
            width: 15%;
            aspect-ratio: 2 / 1;
            position: absolute;
            left: 42.5%;
            background-color: grey;
        }

        /* This div is supposed to be stuck to the bottom of the #container
        div but it's on the bottom of the html element for some reason  */
        #bottomBox {
            width: 15%;
            aspect-ratio: 2 / 1;
            position: absolute;
            left: 42.5%;
            bottom: 0;
            background-color: black;
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="blueBox"></div>
        <div id="redBox"></div>
        <div id="topBox"></div>
        <div id="bottomBox"></div>
    </div>
</body>
</html>

For some reason, the #bottomBox is positioned relative to the html page instead of its container (#container), does anyone know why? Or how I can fix this?

Agent_E11
  • 13
  • 1

1 Answers1

1

Add position: relative to #container

Per w3 docs:

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

Ross
  • 396
  • 2
  • 7