Home > database >  Cannot horizontally center a div element within a div element
Cannot horizontally center a div element within a div element

Time:01-24

I'm developing a layout, and in this layout there are four div elements yellow, green, blue, gray. I want to horizontally center the green div within the yellow div.

Tried "margin: auto;" and other css ways, also w3-css ways as well. But I can't seem to center it. What did I do wrong?

<!doctype html>

<html>

<head>
    <title>Layout</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <style>
    </style>


</head>

<body>
    <div  style="width:100vw;height:100vh">

        <div  style="height:47px; width:100%; position: absolute;  z-index:2">
            <div  style="background-color: #2f4f4f; ">
            </div>
        </div>

        <div  style="height:100%; width:100%; position: fixed; ">

            <div  style="height:100%; width:296px; z-index:1; background-color: yellow; " id="sidebar">
                
                <div
                    style="position: absolute; top: 47px; width:280px; height:500px; margin: auto; background-color: green">
                </div>

            </div>

            <div  style="height:100%; ">
                <div style="height:97%; background-color: blue;">
                </div>

                <div style="height:3%; width:100%; background-color: gray;">
                <div>

</body>

</html>

CodePudding user response:

position: absolute;
top: 50%;
width: 280px;
height: 500px;
margin: auto;
transform: translateY(-50%);
background-color: green;

CodePudding user response:

You could replace your green div with the following code:

<div style="margin: auto; position: absolute; top: 0; bottom: 0; width:280px; height:500px; margin: auto 0; background-color: green"></div>

The main changes here are using top: 0 and bottom: 0 value with margin: auto 0. This will ensure the div remains vertically centred within its relative parent.

  • Related