Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

Centering containers using proper XHTML/CSS?


:P
On this page:

In my quest to clean up my HTML act from older applications, I'm trying to move all my HTML in several applications over to XHTML and as much as possible eliminate all the various VS.NET warnings for legacy HTML constructs. For the most part this has been pretty easily done by removing most attributes and sticking them into CSS properties and either using style sheet classes right off or using style tags on controls.

 

There are a however a few things that I'm having a hard time with. The most common problem I run into has to do with centering content. Specifically centering content like tables and <div> tags. In the past I often used the <center> tag which is now obsolete.

 

It still works in browsers, but officially it's deprecated. XHTML also renders anything that is centered in the parent container very differently than HTML does – it by default inherits the parent container's alignment so if you do something like this:

 

<center>

<div style="width:300px;background:green;height:300px; ">

here's some text

</div>

</center>

 

You'll get the text inside of the <div> also centered. That's easy to fix by adding an explicit text-align:left style to the <div> tag, but in conversion this can really bite you.

 

Back to the <center> replacement.

 

It looks like there's a float style attribute that can be applied to a container such as a div tag to make it go right or left.

 

<div style="width:300px;background:green;height:300px;float:right;">

here's some text

</div>

 

That works great actually, but it doesn't have a value for center.

 

If you're not dealing with a DIV tag using <p style="text-align:center"><div>..</div></p> works. But a <div> tag is not allowed inside of a <p> tag.

 

Ok, so I can see a way to do this like this:

 

<div style="width:100%;text-align:center">

    <div style="width:300px;background:green;height:300px;float:middle;">

    here's some text

    </div>

</div>

 

which seems like overkill for such a simple thing.

 

Anybody know of a better way?

 

 

FWIW, here are a couple of others that I have in many places and weren't real obvious:

 

TD nowrap="nowrap"

CSS style: white-space: nowrap

 

IMG align="right"

CSS style:  float: right;

 

The IMG align has the same limitation as above - you can't center using the float CSS tag.

 

 


The Voices of Reason


 

Andy
April 26, 2006

# re: Centering containers using proper XHTML/CSS?

For the outer div tag try setting the margin to: margin: 0px auto 0px auto;


Rick Strahl
April 26, 2006

# re: Centering containers using proper XHTML/CSS?

Andy - tried but that doesn't center the inner div...

Edgardo
April 26, 2006

# re: Centering containers using proper XHTML/CSS?

You don't need to specify the width on the outer div if its 100%, only text-align: center.

For the inner div you set the width and the margin (like andy suggested), though I set it as margin: 0px auto.

This works on IE6/7, FF and Opera as far as know.

Maciek
April 26, 2006

# re: Centering containers using proper XHTML/CSS?

Hi Rick.
The main reason to use a CSS and XHTML instead of old table-layout is semantic. For example:
Div is for grouping some logic part of the web, and the p is for displaying a part of the text, so:

<div style="width:100%;>
<p style="margin: 0 auto;">text text text</p>
</div>

Now, for example googlebot will be much more happier :)

If you want to have img with margin:0 auto, you will have to mark this img as display:block;. By default img is inline element.

Hope it helps :)


Rick Strahl
April 26, 2006

# re: Centering containers using proper XHTML/CSS?

Sorry guys, the margin bit is lost on me. What is the margin doing that affects the text alignment? Auto Margins will just use stock margin values?

Ultimately this works:

<div style="text-align:center;">
<div style="width:300px;background:green;height:300px;">
here's some text
</div>
</div>

but I was hoping there'd be a way to do this without having to nest <div> tags.

Frank Zehelein
April 26, 2006

# re: Centering containers using proper XHTML/CSS?

The following Code will center any div - just with the use of one div (no nesting) in IE 5.0 and higher and any modern browser:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="de">
<head>
<meta http-equiv="content-language" content="en" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css" media="all">

body
{
width: 100%;
height; 100%;
text-align: center;
}

#center
{
width: 300px;
margin: 10px auto;
background-color: green;
text-align: left;
}


</style>
</head>
<body>
<div id="center">
some content to fill the div. some content to fill the div. some content to fill the div. some content to fill the div. some content to fill the div. some content to fill the div. some content to fill the div. some content to fill the div. some content to fill the div. some content to fill the div. some content to fill the div. some content to fill the div.
</div>

</body>
</html>



See it in action here:
http://www.zehelein.de/static/center.html

Explanation:
the fix with does what it is meant to do - give the box a fixed size. The margin 0 auto tells to have a margin on the top and bottom of zero. Auto means to calculate the left and right margin in the browser - so distribute the space equally to the left and right (so to center it).

That does not work in IE 5. So we use a bug here. IE 6 centers block level elements (like div etc.) with text-align: center (which should only affect inline elements). So we center the div that way and undo it with text-align: left again.

100% height and with is to get the same behaviour in all browsers.

the xhtml prolog and header is to get valid xhtml strict and tell IE 6 to not use Quirks mode

Russ Garner
April 26, 2006

# It's all about the widths

The best way to visualise these things (for me) is to download a copy of the Firefox Web Developer Toolbar from http://www.chrispederick.com/ and use the Edit CSS feature along with custom outlining of tags/block-level elements. This way you'll see what works with your CSS "live" and get a good idea of how the box model is working.

This will work:

<div style="width: 25%; margin: 0 auto;">
Roughly centered text here
</div>

It's all about the width. A div is a block-level element which means by default it's sized at 100% of its container width. Margin: 0 auto; will perform a centering, but if you center something that's already as wide as the container you'll see no effect.

Also, don't be tempted to use float - this is something to allow you to flow other elements around an element. It's an important CSS layout tool, but it's also a great thing to use casually if you *really* want to get bitten later ;)

Rick Strahl
April 26, 2006

# re: Centering containers using proper XHTML/CSS?

Ok, I don't know what I was doing before, but margin:0px auto; does work to center. It didn't work in one of my situations, but it does now that I tried a simpler scenario.

While we're at it with the CSS wizards here <g>: How about centering an image with out wrapping it?

Edgardo
April 26, 2006

# re: Centering containers using proper XHTML/CSS?

Also, it depends on the browser (here comes IE to the rescue again), if I remember correctly when I was testing all this a long time ago margin: 0px auto does not work on IE. Firefox AND Opera do *not* center a div based on the outer div's text-align: center value, that is why you need to set the left and right margin to auto.

"but I was hoping there'd be a way to do this without having to nest <div> tags."

The outer div is just one of the too many hacks you need to do to get a fancy XHTML strict CSS-based website to work on IE6 (hopefully *not* IE7!).

Frank Zehelein
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

just try my solution (see above) - it works without extra markup in all browsers - even IE (and is of course xhtml strict)

For images it should be enough to specify

display: block;

haven't tried it though.

Frank Zehelein
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

ok - tested it and included it in the above example:

http://www.zehelein.de/static/center.html

#centerimage
{
margin: 10px auto;
display: block;
}

[snip]

<img src="fishlogo.gif" alt="some image" id="centerimage" />

Joe Brinkman
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

I have used the auto technique many times, but every time I hear someone like Frank discussing how we have this code for IE and this code for Netscape and oh by the way you need another hack to fix IE 5, then I just want to drop CSS altogether and stick with POT (plain old tables). The situation with CSS seems like Web Dev circa 1999.

Frank Zehelein
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

you can ignore IE 5 if you like. It is nothing different to tables. You also have enough problems with tables to get the layout for all the browsers identically.

You have to decide what is more important to you. CSS and the benefits (somethings are not possible with tables) separeation from content and design, better search engine results and so on.
Or Tables with for most persons easier Layout, but worse maintainability and worse search engine results (let alone the accessibility, rendering on mobile devices and things like that).

But for me i think it is easier to get a layout look good for all browsers in CSS than in tables - even though there are some different interpretations betwenn modern browsers and IE less and/or equal 6.

But if no one uses it (at least not the majority of pages) css wont get any better in browsers and we can never use it...

Oskar Austegard
April 27, 2006

# re: Centering containers using proper XHTML/CSS?


Gabe
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

<ramble>
I for one don't see the problem with table based layouts. I can easily create sophisticated pages the render the same in all browsers and don't have to wade through all of the confusing hacks to get something as simple as horizontial (or god forbid vertical) centering to happen. Don't get me wrong, I like CSS and the ability to seperate content from presentation, however I don't know why the purist have to banish table layouts from existance. In the real world, it's often just not practicle to seperate layout from content, especialy for dynamic web apps. I for one am sticking with transitional HTML 4.x. I can have my cake and eat it to. THe only downside is working with the designer in VS 2005 is much more difficult, as only generates XHTML markup. For example, lets say you want to emphasize a piece of text on the page by making it red. How is a font tag worse than a span tag with a style attribute?
</ramble>

Eric C.
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

Gabe, I agree. I can put a good layout together using tables, and it is sooo much easier. BUT, it makes thinks a bit harder in the long run. Tables are only indended for displaying tabular data (ala Excel, or our good friend FoxPro).I'm not going to go into full details, but seperating content from presentation is very crucial. Here are some good articles for digestion:

http://davespicks.com/essays/notables.html
http://www.stopdesign.com/articles/throwing_tables/
http://www.alistapart.com/stories/betterliving/
http://en.wikipedia.org/wiki/Tableless (very good article)
http://www.csszengarden.com/ (Amazing proof of concept, same XHTML markup, vastly different designs)


And my fav, ESPN's proof of concept of css for layout:
http://www.mikeindustries.com/blog/archive/2003/06/espn-interview

Eric C.
April 27, 2006

# re: Centering containers using proper XHTML/CSS?


KimF
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

Hi there,

I am a lowly web designer-type working with asp.net developers who will argue into the ground that going tableless is not practical. One answer is to use tables with CSS applied, see http://www.projectseven.com/tutorials/css/css_td/index.htm.

RE: Centering, the code posted above with a body tag set to text-align center and an id with text-align left illustrates an easy way to center a page. Understand the concept -- an outer container (body) set to center everything, an inner container (div with id in the example) set to left-align. You can apply the same idea to any elements you wish to center, just wrap them in a div that centers them and if necessary use an inner div set to text-align left(or set the element inside the div, like a paragraph or table, to align left, or create a CssClass that does this), and away you go.

HTH!
Kim


Eric C.
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

Centering with CSS is not fun, here are some working examples of a centered layout:

Live site:
http://www.dacardworld.com/

New Layout for the above site:
http://www.dacardworld.com/include/new_test/sports.html
http://www.dacardworld.com/include/new_test/itemlist.html

Steve from Pleasant Hill
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

A table-less world would seem a bit drab. Why are tables bad? Why is there this fervor to not use them at all? Or is it really all the other tags (mis)used with tables?

Is it OK for me to use tables and apply CSS where ever possible?

Different output between browsers tires me, when I really need to be working on the business logic.

The ESPN article was very interesting. How badly does table use inflate the payload vs. CSS only? Or again, is it the non-use of CSS, that is, using various mark up tags in place of CSS that are the culprit.

Disclaimer: I am an ex-Win32 developer (I wouldn't even do web development until .NET just so I could set a break-point).

Rick Strahl
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

Steve, actually I have wondered the same thing. DIV tags are very useful but using them exclusively to create tabular like layout is overkill and actually makes things more difficult in many cases.

IAC we're not likely to get away from tables for things like data grids and lists of various sorts.

There are some advantages to divs over tables such as that div don't have to wait for the complete table to render (a big issue in something like this BLOG for example, where there's a lot of content in one 'panel').

But truth be told issues like this centering have been the main reason I've continued to used tables as layout elements. Until you figure out all of the CSS permutations and can get comfortable with them it's hard to get excited about all the quirks in the CSS/DOM rendering models in regards to DIV.

TABLEs at least render fairly consistent across all browsers. Divs - not so much.

Rick Strahl
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

Gabe, I would argue that even if you're using HTML 4.01 you should use CSS as much as possible and not use things like Font tags. For one thing it's more consistent and much easier to maintain because styles are applied to the element as opposed to be wrapped around the element you're styling. This is part of the reason why I asked this question - I prefer to do everything on the element itself either with a style attribute or CSS class.

As I said above I'm not sold on removing all table layout either and tables are certainly legal even in XHTML - but they do get reigned in terms of attributes that can be applied to them.

The biggest problem with moving to XHTML is not that you can't do things - it's that stuff that you've learned in the last 10 years doesn't work anymore and has to be expressed differently.

I don't think that's necessarily a bad thing, but certainly a time consuming one if you move an application. I doubt I'll be able to get my apps to be 100% clean, but I'll shoot for a close call at least.

Frank Zehelein
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

IAC we're not likely to get away from tables for things like data grids and lists of various sorts.

I think there is often a bit of misunderstanding. Tables are NOT "evil". They are perfectly suitable for tabular data (e.g. datagrid).

For Lists (with one row) or nested lists i think it is much easier to really use ul/li lists (or ol/li) lists to mark them up and get consistent styling for all nestings.

Also i am not using tables for layout, i think if you are using only one table for the layout (header, footer, left column and content e.g.) it is in no way as evil as many claim it to be. Most screen readers work well with that. Biggest problem i think are here mobile devices as they can better serialize the layout from div - but i am not 100% sure of that.

And yes - it is hard. It is also hard to get your Software 100% perfectly programmed - at some point it is simnply much easier to apply that 80/20 or 90/10 rule (as only few peoply are willing to pay for that last 10% that much money - or time)

Russ Garner
April 27, 2006

# re: Centering containers using proper XHTML/CSS?

For me it's all about payload - table-heavy designs add both visual and bandwidth-related inefficiency to markup.

I'll agree that CSS has a learning curve. I successfully resisted it for several years ;) Once you get the box model, though, and use something like Web Developer Toolbar, it quickly gets vastly more productive than a lot of table-based layout schemes.

Like Frank says, tables aren't "evil", they should simply be used to represent tabular data. DataGrids are fine, but the default ASP.NET 2.0 TreeView (which renders as a table) *is* evil - that tree is more properly represented as a list, but we're going to have to wait for ScottGu's team to release the CSS Control Adapter toolkit to transform the evil control into something a CSS designer would want to see.

For things like form layout, though, CSS is still the way to go, even if it feels like you're simulating a table at first. Try something like

<style>
div.field { margin-bottom: 1.5em; clear: left; }
label { width: 25%; float: left; }
</style>

<div class="field">
<label for="txtCustomerName">Customer Name</label>
<input id="txtCustomerName" type="text">
</div>

With this scheme you could replace float: left with display: block on the label definition and have your labels appear above your fields immediately. Not something that you could do in a table layout without a significant amount of td dancing ;)

michael
May 08, 2006

# re: Centering containers using proper XHTML/CSS?

margin: auto ; is your friend for centering div's as long as your not using a float.

if you use float, use them with combinations of
float: left; and overflow:hidden;

Pete D
May 22, 2006

# re: Centering containers using proper XHTML/CSS?

This is a common arguement that coders have with designers. "Whats wrong with table layout?" Well theres plenty wrong with it if used incorrectly. If you just want a simple header,footer, side bar and main content layout then use tables by all means. If on the other hand you are using tables within tables and using spacer gifs everywhere then its time to think about looking into CSS more. There are so many benefits from moving away from masses of table code (a quick point here, don't assume this means that you can't use tables at all, I'm not saying you should re-create a table layout with thousands of divs instead of td's thats just madness. If you start doing that then your whole markup could probably do with a re-think).

* Reduced page weight, you need less HTML/XHTML to layout the page (no more rowspans,colspans,nowraps etc).
* All the presentation is seperated, what to change the look of your page, easy just change to CSS (check out http://www.csszengarden.com/ for some examples of this. One XHTML file made to look VERY different using CSS alone.
* The presentation markup is downloaded only once as its a seperate file and cached on the client
* If done right it is accessable to screen readers and makes more sense, jumping around to different TDs that don't seem to be linked can be very disorientating and frustrating, go on give it a go on your site and see what I mean.
* Using CSS to seperate out presentation logic should be seen as a good practice, no different to the good practises we would us when writing our code (Don't Repeat Yourself - DRY, De-couple as much as you can, encapsulate related items etc. If you look at it as a coding tool rather than some toy to keep the crayon boys and girls happy then you will start using it as you should.

There are some fantastic books out on the subject, some are very dry but by far the best three are listed below in order. They are very easy to read and are packed with invaluable knowledge, the Dan Cederholm books are constantly by my PC.

Buy them, read them and then you'll get it.

Cheers

Pete


Designing with Web Standards by Jeffery Zeldman:

http://www.amazon.co.uk/exec/obidos/ASIN/0735712018/qid=1148376843/sr=8-1/ref=sr_8_xs_ap_i1_xgl/026-1606448-9624412

Web Standard Solutions and Bullet Proof Web Design by Dan Cedarholm:

http://www.amazon.co.uk/exec/obidos/Author=Cederholm%2C%20Dan/ref=pd_sima_dp_1_1/026-1606448-9624412

Bob Fitzhugh
June 22, 2006

# re: Centering containers using proper XHTML/CSS?

There is a simple way to center a table within a surrounding element (such as a div). Using CSS styles, set the following for the table:

margin-left:auto
margin-right:auto

Not very intuitive, but it works, and supposedly, it conforms to the CSS standards.

Bob

Dave S
June 13, 2008

# re: Centering containers using proper XHTML/CSS?

This is what I use:


.centerThis {
margin-left: auto;
margin-right: auto;
width: auto;
}

&lt;p class="centerThis"&gt;


Works for probably 80% of markups. If there is an odd one on the page that slides to one side or the other, just give it an overriding width.

&lt:p class="centerThis" style="width: 300px"&gt;

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2025