Archive for July, 2009

The Pain of Vertical Alignments with CSS

Friday, July 24th, 2009

When it comes to vertical alignments for web contents, CSS 2.0 doesn’t help as it was not supported by its nature. There are quite a few Vertical Alignment with CSS hacks out there but frankly speaking, none of them are clean cut and most importantly, works awkwardly in IE.

I’d been dealing with such problem quite a while and also coping with strict customer requirements such as IE6 and minimal structural modifications on HTML. Luckily, an example from Katz Web Services came to the rescue. It was the best solution I see so far (with minimal codes). The original example was encapsulated into a JQuery plugin which can be easily implemented. Anyway, what I want to mention is that, the core sets the “margin-top” CSS property by calculating the distances between the element and the element’s parent, then halved.

In my scenario, instead of applying JQuery, I created a new class defining the “margin-top” property, then apply the class across elements to be vertically aligned. I utilized CSS expression to dynamically calculate the selected element’s and its parent’s height, then do the calculations.

.valign-center
{
margin-top:expression(((this.parentNode.clientHeight-this.clientHeight)/2) +”px”);
}

I found that CSS “expression” property is quite handy when dealing with situations such as non fixed widths and heights. Too bad that such property works only on IE (Though I only need to deal this on IE6). So, to deploy such method for cross browser compatibality, the best way would still be applying the JQuery plugin by Katz Web Services. Anyway, it’s still a lovely solution that eases my pain. :)

Oh yeah, CSS3 is going to support for vertical alignments. Just hope that future web browsers could adopt it well…