Search code examples
htmlcsscss-positioncentering

How do I center an absolutely positioned element?


div {
    width: 400px;
    height: 400px;
    background: yellow;
    z-index: 99;
    margin: 0 auto;
}

I have a div pop message, it will be on top layer and position middle of page.

however if i set position:absolute; z-index:99; it will be on top but margin:0 auto; wont work.

how can i keep it on top of layer and also display at middle?


Solution

  • Centering an element with position: absolute; applied works by using two nested elements (demo).

    1. The first element will be positioned absolutely to place it above all other elements
    2. The second element just works like you would expect it: Use margin: 0 auto; to center it.

    HTML:

    <div class="outer-div">
        <div class="inner-div">
            <p>This is a modal window being centered.</p>
        </div>
    </div>
    

    CSS:

    .outer-div {
        position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        z-index: 13;
    
        /*
         * Setting all four values to 0 makes the element as big
         * as its next relative parent. Usually this is the viewport.
         */
    }
    
    .inner-div {
        margin: 0 auto;
        width: 400px;
        background-color: khaki;
    }