Monday, August 29, 2011

Advanced CSS3 Tutorial 4: Align


In CSS, several porperties are used to align elements horizontally.

Center Aligning Using the margin Property

Block elements can be aligned by setting both the left and right margins to "auto".
(margin:auto does not work in Internet Explorer 8 unless !doctype is declared.)

Setting the left and right margins to auto specifies that they should split the available margin equally, The result is a centered element:

.center
{
margin-left:auto;
margin-right:auto;
width 70%;
background-color:#353535;
}

Note: Aligning has no effect if the width is 100%; In IE5 there's a margin handling bug for block elements.

Left and Right Aligning Using the position Property

One method of Aligning elements is to use absolute positioning:

.right
{
position:absolute;
right:0px;
width:300px;
background-color:#353535;
}

Absolute positioned elements are removed from the normal flow, and can overlap elements.

Crossbrowser Compatibility Issues

When aligning elements like this, it's a good idea to predefine margin and padding for the <body> element. This is to avoid visual differences in different browsers.

There is a problem with IE8 and earlier when using the position property. If a container element (in our case <div class="container">) has a specified width, and the !DOCTYPE declaration is missing, IE8 and earlier versions will add a 17px margin on the right side. This seems to be space reserved for a scrollbar. Always set the !DOCTYPE declaration when using the position property:

body
{
margin:0;
padding:0;
}
.container
{
position:relative;
width:100%;
}
.right
{
position:absolute;
right:0px;
width:300px;
background-color:#b0e0e6;
}

Left and Right Aligning Using the float Property

Another method of aligning elements is to use the float property:

.right
{
float:right;
width:300px;
background-color:#b0e0e6;
}

9 comments:

  1. What happens if I change the width px?

    .right
    {
    position:absolute;
    right:0px;
    width:300px; <-------
    background-color:#353535;
    }

    ReplyDelete
  2. cheers, another skill in my arsenal

    ReplyDelete
  3. Sweet, cheers dude! I'll give it a go.

    ReplyDelete
  4. god, this sure makes me wish i was smarter

    ReplyDelete
  5. when i had exam in university it was HTML + CSS. this article would really helped me then but i still scored A, but took me long enough to understand how to do the exam.

    ReplyDelete
  6. Wow long tutorial. I'm starting to get it though!

    ReplyDelete
  7. I've been designing a website for an artist and this will help a ton with getting the gallery to display the way I want it! Thanks!

    ReplyDelete