Search code examples
htmlcsscenter

How to perfectly center a div in a container


The HTML code is :

<div class="header">

        <div class="div1">
            Division 1
        </div>

        <div class="div2">
            Division 2
        </div>

        <div class="div3">
            Division 3
        </div>

</div>

And the corresponding CSS code is:

.header{
    border: 2px solid red;
    text-align: center;
    height: 100px;
    overflow: hidden;
}

.div1{
    height: 150px;
    width: 150px;
    background-color: green;
    float:left;
}   

.div2{
    height: 150px;
    width: 100px;
    margin: 0 auto;
    background-color: orange;
    display: inline-block;
}

.div3{
    height: 150px;
    width: 50px;
    background-color: blue;
    float: right;   
}

It starts the div2 from the center of the screen but proceed in right direction. I want to make the div2's center on the center on the screen.

The current output is shown here: output


Solution

  • Make header position:relative and div2 position:absolute left and right to 0 see this fiddle. https://jsfiddle.net/xwzyoqn3/1/

    .header{
        border: 2px solid red;
        text-align: center;
        height: 100px;
        overflow: hidden;
        width:100%;
        position:relative;
    }
    
    .div1{
        height: 150px;
        width: 150px;
        background-color: green;
        float:left;
    }   
    
    .div2{
        height: 150px;
        width: 100px;
        margin: 0 auto;
        background-color: orange;
        display: inline-block;
        position:absolute;
        left:0;
        right:0;
    }