Re: An HTML question <<centering DIVs>>

by "Mike H" <ironmike(at)inav.net>

 Date:  Tue, 29 Oct 2002 02:26:28 -0600
 To:  "Techniques" <hwg-techniques(at)hwg.org>,
"Octavian Rasnita" <orasnita(at)home.ro>
 References:  microsoft
  todo: View Thread, Original

----- Original Message -----
From: "Octavian Rasnita" <orasnita(at)home.ro>
Subject: An HTML question

> I want to put some HTML code in an <div> block, to put that block in the
> middle of the page (center aligned) but to align the text from that block
to
> the right of the block.
>
> I've tried to use:
>
> <div style="text-align: center;">
> <div style="text-align: right;">

> but the text is right aligned to the margin of the screen, not to the
margin
> of the  first <div> block.
>
> I want the first <div> block to be as wide as the text from it.
>
> Thank you for any tips.
>
> Teddy's Center: http://teddy.fcc.ro/
> Email: orasnita(at)home.ro


Hello, Octavian;

IT IS possible to horizontally center a <.div> on the page, and it is
possible to right-align the text in it, BUT you must declare some kind of
width for the div, either in per-cents or pixels. This width is necessary
for the browser to set limits for the width of the div. Otherwise the div
will get wider as the text gets longer until the edges of the centered div
reach the edges of the screen or the padding of the outer div.

Here is some sample code which will center a div:

div.container{
     margin: 10px, 0px;
     padding: 10px;
     background-color: #fff;
     text-align: center;
}

div.content{
     margin: 0px, auto;
     text-align: right;
     background-color: #eee;
}

The "secret" is in using the "auto" value for the margin of the inner div.
This doesn't work in IE 5. The "text-align: center" of the outer div will
center block elements inside the container in IE 5. (I know, it's a
workaround.)

One other approach is to use a <.br /> tag to force line breaks where you
want them. The longest line will set the width of the inner div, unless that
line is wider than the available space in the outer div.

For more information on centering divs see

http://www.bluerobot.com/web/layouts/

The very last line has links to sample code for two methods of centering.

HTH!

Mike Hopkins
ironmike(at)inav.net

HWG hwg-techniques mailing list archives, maintained by Webmasters @ IWA