Search code examples
htmlcssposition

div inside another div positioning in center


I want to make a div which has two divs inside itself, and also I want to position them ALL in center using the margin:auto property. But it's not working properly. I've searched the web for this problem but I couldn't find a good answer. What have I missed?

<style>
        body{
            padding: 0px;
            margin:0px;
        }
        .top{
            padding: 0px;
            margin:0px;
            width:100%;
            height:50%;
            background-color: lightblue;
        }
        .top div{
            margin:auto;
            padding:0px;
            box-shadow:2px 2px 2px black;
            width:200px;
            height:200px;
            background-color: red;
            border-radius:20px;
        }
        .top div div{
            margin:auto;
            padding:0px;
            box-shadow:2px 2px 2px black;
            width:100px;
            height:100px;
            background-color: red;
            border-radius:20px;
        }
</style>

to whom asked for html:

<body>
    <div class="top">
        <div>
            <div>
            </div>
        </div>
    </div>
</body>

Solution

  • Please update you following class. Please add positions to .top div {position:relative;} and update the .top div div class.

    Html

    <div class="top">
             <div><div></div></div>
    </div>
    

    Css

    body{
                padding: 0px;
                margin:0px;
            }
            .top{
                padding: 0px;
                margin:0px;
                width:100%;
                height:50%;
                background-color: lightblue;
            }
            .top div{
                margin:auto;
                padding:0px;
                box-shadow:2px 2px 2px black;
                width:200px;
                height:200px;
                background-color: red;
                border-radius:20px;
              position:relative;
            }
            .top div div{
                margin:auto;
                padding:0px;
                box-shadow:2px 2px 2px black;
                width:100px;
                height:100px;
                background-color: red;
                border-radius:20px;
                vertical-align: middle;
                margin: auto;
                position: absolute;
                top: 0;
                left: 0;
                bottom: 0;
                right: 0;
            }
    

    Demo here