Blog

Using CSS to align an element both horizontally and vertically

Posted on March 9, 2010 Posted in blog, web development
Using CSS to align an element both horizontally and vertically

I’ve always been a little frustrated about why aligning elements vertically with CSS can be a hassle. I mean it’s a straight forward and simple task right? I am sure there are good reasons behind it.

Anyway, back in the days when tables used to dominate website design (probably still does!), it was very easy to horizontally and vertically align elements. You simply did the following:

<table width=100% height=100%>
<tr>
<td align=center valign=center>element goes here</td>
</tr>
</table>

The good old “valign” property has helped and still does in many different ways.

Well, the days of designing a layout using a table is just wrong for all sorts of reasons.

To align elements both horizontally and vertically in CSS you can apply the following to your element:

.hor_ver_align {
position:absolute;
display:block; // only need if it’s an inline element
height:200px; // need to know the height
width:300px; // need to know the width
top: 50%;
left: 50%;
margin-top: -100px; // half the value of your height
margin-left: -150px; // half the value of your width
}

This should work in most cases but if you don’t know that height/width of the element then you can use jQuery to find it out dynamically.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to StumbleUpon

No Comments »

Leave a reply

Your Name
July 14, 2009

Name

Mail (will not be published)

Website

Message

* Name, Email, and Comment are Required