Search code examples
csspositionalignment

CSS: center a fixed div


I have a class for a fixed positioned div to stay at the bottom of the view port. I am trying to make the width automatic so that as the div changes width, it remains centered.

.box {
position: fixed;
width: 80%;
bottom: 20px;
left: 50%;
margin: 0 0 0 -40%;
max-height: 50%;
overflow: auto
}

Any ideas? I tried a container with text-align: center then display: inline, but it produced crazy results.


Solution

  • .box {
        position   : fixed;
        left       : 10%;
        right      : 10%;
        bottom     : 20px;
        max-height : 50%;
        overflow   : auto;
    }
    

    You can use left and right together to center the element (instead of using width).

    If you want to use width then you can do this:

    .box {
        position   : fixed;
        left       : 10%;
        width      : 80%;
        bottom     : 20px;
        max-height : 50%;
        overflow   : auto;
    }
    

    If you want to center HTML inside the fixed element you can do this:

    .box > div {
        width      : 50%;
        min-width  : 150px;
        margin     : 0 auto;
        text-align : center;
    }
    

    Here is a demo: http://jsfiddle.net/dFXt5/