Horizontal centering

From Joomla! Documentation

The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Horizontal centering is achieved with CSS in one of two ways, depending on what you are centering.

For the first example, let's say you have a horizontal menu at the top of your page that you want centered in your layout. You would do it with a block of code in the linked CSS file:

#horz_menu {
   margin: auto;
   width: 800px;
   height: 25px;
}

The auto value in the margin attribute centers the item, so this would create a menu area that is 800 pixels wide and 25 pixels tall and would be centered in whatever space it is placed in.

If you need to add some margin space above and below the menu and still keep it centered you would adjust the code:

#horz_menu {
   margin: 20px auto 20px auto;
   width: 800px;
   height: 25px;
}

This would add 20 pixels of space on the top and bottom of the menu while keeping the left and right margin in a centered mode.

The second example is when you simply want to center text, in which case you just add the text-align code.

#horz_menu a {
   padding: .75em 0 .52em 0;
   font-size: 0.8em;
   font-weight: bold;
   color: #0033CC;
   background-color: transparent;
   text-align: center;
}

This would cause any links within the horz_menu div tag of the HTML code to be centered in the horizontal menu. They would also have .75em of padding above and .52em of padding below them.

These same techniques work for the overall page layout as well. Let's say you want the shell content area of your page to be 900 pixels wide and to be centered on the page and that you want the headline to be centered within it. Your CSS code would look like this:

#page_container {
   margin: auto;
   width: 900px;
   background-color: #FFFFFF;
   border: 1pt solid #660000;
}
#page_container h1 {
   margin: 50px 0 20px 0 ;
   font-size: 1.25em;
   font-weight: bold;
   color: #0033CC;
   background-color: transparent;
   text-align: center;
}

This would create a page that has a main content box centered in the browser window with a white background and a brown border.

Any text inside a h1 tag that is inside the page_container div tag in the HTML code of the page would also be centered inside that main content box.

Of course the example above is simplified for demonstration and you would have more structure involved (left column, right column, etc).

So as you can see, horizontal centering for structural items is achieved with the margin attribute whereas horizontal centering for text items is achieved using the text-align attribute.