Search code examples
csscss-positioncentering

CSS Centering - div with inline buttons that can be at top and bottom of screen


I'm trying to make a control panel which has a couple of buttons that have to be inline. When the width of the window is large the buttons are centered at top of the screen and when the width of the windows is small they are centered at the bottom of the screen. During some instances I remove some of the buttons but the div still has to be centered.

  1. I have to use absolute positioning, right?

When the control panel is at top I should have

#control-div {
    position: absolute;
    top: 0;
}

And when the control panel is at the bottom it should be

#control-div {
    position: absolute;
    bottom: 0;
}

Here comes the problem. I want the div to be centered. I can't know what the width of the div is since some buttons might be removed or added. It must always be centered. So what I've tried was to use two divs

#outer-div {
    position: absolute;
    left: 50%;
}

#control-div {
    position: absolute;
    left: -50%
}

This works for arbitrary widths of the control div. But now the problem is that the buttons are not inline anymore. So what's the solution?

Here is a fiddle of what I'm trying: http://jsfiddle.net/xe8EW/2/


Solution

  • You can use a wrapper to position the menu on the top or bottom. Then you can center the child.

    like so:

    HTML:

    <div class="menu-wrapper">
        <div class="menu">
            <a href="#">Item one</a>
            <a href="#">Item two</a>
            <a href="#">Item three</a>
        </div>
    </div>
    

    CSS:

    .menu-wrapper {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
    }
    @media screen and (min-width: 0) and (max-width: 520px) {
      .menu-wrapper {
        top: auto;
        bottom: 0;
      }
    }
    .menu-wrapper .menu {
        width: 100%;
        text-align: center;
    }
    

    The media query switches between top and bottom alignment. The text-align center makes sure your text is centered w/h specifying a width. It should work as long as you keep your menu elements inline (anchors, inline buttons are fine)

    Note: You might want to replace the position:absolute for a position:fixed if you want the menu to show at all times. But's thats up to your design intent.

    here's a jsfiddle: http://jsfiddle.net/nQmrx/2/

    Update: Didn't know you wanted a background color ;) You can wrap another div for that. http://jsfiddle.net/nQmrx/4/

    .menu-wrapper .menu .background {
        background-color: #9f9f9f;
        display: inline;
    }