Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Standard (dynamic) way to centralize an element in the y-axis

Tags:

html

css

my question is more or less self-explanatory, I am trying to find a standard dynamic way to centralize an element in the y-axis, much like the:

margin: auto;

For the x-axis. Any ideas?

I am talking about the following piece of code, empty page, align one image in the center.

<div id="main" style="display: block;"> 
    <img style="margin: auto; display: block;" 
    src="http://www.example.com/img.jpg" />
</div>

Any help will be appreciated! :)

like image 395
kxk Avatar asked Mar 24 '11 15:03

kxk


2 Answers

Just give up and use tables on this one, with vertical-align: middle. You can get away with just a single-row, single-cell table without feeling too guilty (I sleep like a baby about it). It's not the most semantic thing in the world, but what would you rather maintain, a tiny one celled table, or figuring out the exact height and doing absolute positioning with negative margins?

like image 164
Russell Leggett Avatar answered Nov 12 '22 19:11

Russell Leggett


If you know the height of the element that you're trying to center, you can do this:

img {
  display: block;
  height: 500px;
  position: absolute;
  top: 50%;
  margin-top: -250px; /* 50% of your actual height */
}
like image 36
scurker Avatar answered Nov 12 '22 19:11

scurker