Alex Rivera | Logout

Vertical alignment with CSS

Asked 2011-01-20T10:24:35.983
9

Yeah, yeah, I know this is yet another question about vertical alignment with CSS and it's been done a million times before. Rest assured that I have come across this problem many times and I've already done the reading about various ways to centre vertically with CSS. I'm asking here because none of those ways do quite what I want to do, and I just want to make sure that my suspicion (that CSS vertical alignment is broken and will not do what I want it to do) is definitely correct.

First up, here's my test case: http://www.game-point.net/misc/testAlign/

Here's the criteria:

  • I want to align the 'centred text' vertically, with respect to the DIV containing the 'TestTestTest...' text.
  • I don't want to specify ANY heights.
  • I want both the 'TestTestTest' and the 'Centred text' DIVs to get their heights dynamically, according to the amount of text they have, and the width limit they have.
  • I don't want to use Javascript.

This seems to be impossible even in CSS3, let alone CSS2. The annoying thing is that I'm almost there; the position:absolute; top:-50%; DIV works to set the top of that DIV to halfway down the container DIV. The problem is that the inner DIV, with style position:relative; top:-50%; doesn't do anything to move the content up by half its height, to centre it fully, because CSS says that an absolutely positioned DIV doesn't have a height and therefore top:-50% is meaningless. As far as I can tell, this is just a fundamental flaw in CSS for no particular reason. An absolutely positioned element does have a height, and I don't know why CSS pretends it doesn't. I just wanted to ask whether anyone had any ideas as to how I could achieve the desired effect, pictured at the bottom, given the criteria I outlined above. Ironically IE6/7/8's 'broken' box model, in quirks mode,

Edit
Report

2 Answers

2

The thing is though that vertical handling of content is made that way for obvious reasons, which I'm sure you're already aware of. But you're sort of trying to solve an unsolvable problem, that's not really a problem. (makes sense when you know why things are like they are)

By using absolute position you are just taking content out of the natural flow. It's much better to make everything like it should be with floats and proper sizes or whatever is needed so it degrades nicely and appears ok looking in all devices. Then write two lines of code in jquery to check heights and align everything (which will also work on "all" devices). The 2-3% without JS will need to live with boring sites.

answered 2011-01-20T13:05:52.943
-3
.item {
    height: 40px;
    top: 50%;
    margin-top: -20px;
}

position relative or absolute;

answered 2011-01-20T10:30:20.967

Your Answer