Center Div Inside Div


How to Center Div Inside Div?

Let’s say this is your HTML where you have two div inside a container div.

<html>
    <head>
        <style>
            .container{
                border: 1px solid red;
                height: 200px;
            }

            .div1, .div2{
                border: 1px solid green;
                height: 50px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="div1">
              Div 1
            </div>
            <div class="div2">
              Div 2
            </div>
          </div>
    </body>
</html>

Here is how it looks: enter image description here

To center align contents inside a div you can use use CSS Flexbox layout. To the parent div element class add the following flex layout.

.container{
    border: 1px solid red;
    height: 200px;
    display: flex;
    justify-content: center;
    align-items: center;
}

Here is the complete HTML code,

<html>
    <head>
        <style>
            .container{
                border: 1px solid red;
                height: 200px;
                display: flex;
                justify-content: center;
                align-items: center;
            }

            .div1, .div2{
                border: 1px solid green;
                height: 50px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="div1">
              Div 1
            </div>
            <div class="div2">
              Div 2
            </div>
          </div>
    </body>
</html>

enter image description here