Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering elements vertically within a block

Tags:

css

layout

web

I'm currently redesigning my website from a table layout to CSS. I'm having some problems with what seemed like a very simple task.

The site is simple. A box in the middle of the screen that contains several links.

The old site used <td valign="center"> to center all the links in the box. CSS seems to have no equivalent. I've been centering elements using negative margins like so:

div {
    height: 200px;
    position: absolute;
    top: 50%;
    margin-top: -100px;
}

This works fine when you know exactly how big the element you're centering is, but I need to be able to center the links without knowing how much vertical size the links take up. I just want the aligning in the box to act like text-align: center. Only vertically too.

Current website designed with tables
Current progress on the CSS version

like image 830
user1730358 Avatar asked Oct 09 '12 02:10

user1730358


Video Answer


1 Answers

You have 4, possibly 5 solutions one added to the bottom since it's a combination of different css from your original and js to set height:

  • Use a table cell and center it's content vertically
  • Use display: table-cell; vertical-align: middle; as css for your div
  • Update margin-top every time the div's height changes via javascript
  • Use css3 flexbox (you need to use vendor-specific extensions so it won't work on some older browsers)

Simple example using old-style flexbox - chrome version - add a wrapper div and set it's styling to this:

#wrapper { display: -webkit-box; -webkit-box-align: center; }
#wrapper > div { margin: auto; }

fiddle for this http://jsfiddle.net/gK7YU/

New style flexbox - also chrome version, you'll have to add the other vendor prefixes as well as the version without any prefixes in the final product.

#wrapper { display: -webkit-flex; }
#wrapper > div { margin: auto; }

fiddle for this: http://jsfiddle.net/LeHRD/

The fiddles contain a few more css properties so you can see what is happening easily.

Oh, sorry, you don't need the wrapper div, you can just center vertically any content with flexbox... well, anyway the solution I proposed can be combined with display: table-cell; so it works in older browsers as well.

You can also use absolute positioning with specified height jsfiddle.net/N28AU/1

#wrapper { possition:relative }
#wrapper > div { position:absolute;top:0;right:0;bottom:0;left:0;margin: auto;}

you can calculate height from the contained elements and update it via js if you want to avoid negative margins.

like image 108
xception Avatar answered Oct 16 '22 07:10

xception