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
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:
display: table-cell; vertical-align: middle;
as css for your divSimple 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With