RichF
RichF

Reputation: 135

How to center div block of unknown width?

I am working on removing tables from my site, and just learning the div tricks involved. My home page currently has a centered table nested in another table. Removing the outer table was a bit tricky for someone just learning non-table methods, but it's done.

My problem is, the inner table is super-easy to center ("margin:0 auto" in the CSS), but its div equivalent is not. The div will center if I specify an absolute width (such as 640px), but since I'm designing with the user's font size (not something I specify), I don't know how wide it will actually be for a given user.

I've simplified the home page and have it online (test.html and HoH.css Here is an overview image of test.html.

Sorry for all the links. But with a floaty thing inside another floaty thing, I don't know what is relevant. The file test.html contains 63 lines of formatted HTML. The 640px hr is there for reference only; it will not be part of the final page.

PS: I'm removing the tables because when I asked for site reviews, the first comment almost everyone had was, "get rid of the damn tables".

Upvotes: 1

Views: 244

Answers (2)

ggdx
ggdx

Reputation: 3064

use CSS and jQuery -

css -

#divID{ left:50%;}

jQuery -

(function(){
var marginLeft = $('#divID').width();
$('#divID').css('marginLeft','-'+ marginLeft /2 +'px');
});

Upvotes: 0

antejan
antejan

Reputation: 2624

Probably you shouldn't worry about users font size because all modern browsers zoom whole page, not only font size, and everybody will be happy with your fixed width.

Also you can use EM values instead of PX, 1em = font size in px. You can change 640px to 40em if you have 16px font size. If someone have for example twice bigger font, he will get twice wider block.

And if you want css-solution for unknown width block centering, you can use inline-block and text-align:center: http://jsfiddle.net/rBc4T/

Upvotes: 3

Related Questions