Introduction
In the good ol' days, using nested tables would get the
trick done for centering your content. Unfortunately, that
was (and still is) a painful experience for certain browsers
and screen readers. This tutorial will give you some
examples for what the pro's do to get their content
centered.
Marginally Easy
This example focuses on the use of margins. Their
value can be exact or relative. When a block level object
expresses a margin value, the external CSS code looks like
this:
- div#idname
{
- margin:
1px;
- }
This expression is telling the browser "The div tag with
the id called 'idname' will have a margin of 1 pixel." It is
extremely important to note that this means all four margins
- the top, right, bottom, and left - will receive a value of
1 pixel. To be more precise, we can extend the values out a
little more by doing this:
- div#idname
{
- margin-top:
1px;
- margin-right:
2px;
- margin-bottom:
1px;
- margin-left:
2px;
- }
Whoa. That's way too much code. Did you know we can
achieve the same thing in only one line? Here's how:
- div#idname
{
- margin:
1px
2px
1px
2px;
- }
It circulates from top to left in a clockwise motion.
Therefore the code is literally saying, "The div tag with
the id 'idname' will have a top margin of 1 pixel, right of
2 pixels, bottom of 1 pixel, and left of 2 pixels."
Hmm...There's a pattern here: My top and bottom values are
the same, as well as my left and right. This means we can
condense our code even more!
- div#idname
{
- margin:
1px
2px;
- }
Sweet. So now my top and bottom margins are 1 pixel, and
my left and right margins are 2 pixels.
What does this all mean, Kris?
Remember when I said earlier that margins can be
relative, and not just fixed? Well, a relative left and
right margin is our goal. If we can some how declare that
our left and right sides have an equal numbered value, the
cushion on both sides will be dynamically the same!
Therefore, it'll be centered.
One last thing to remember is that you need to declare a
width for the div, or else they browser won't know how much
to put on either side. But you have probably already figured
that out.
Lets take a look at our final code:
- /* external CSS */
- div#container{
- margin:
0
auto;
- width:
550px;
- }
-
- <!--
(X)HTML
code
-->
- <div
id="container">
- <p>this
is
centered!</p>
- </div>
Tada! As long as the container div is the highest div
containing any sort of content (hierarchy-wise), you'll be
centered!
Developer's Notes