tags:

views:

3075

answers:

4

I'm trying to horizontally center a <div> block element on a page and have it set to a minimum width. What is the simplest way to do this? I want the <div> element to be inline with rest of my page. I'll try to draw an example:

page text page text page text page text
page text page text page text page text
               -------
               | div |
               -------
page text page text page text page text
page text page text page text page text
+2  A: 
.center {
   margin-left: auto;
   margin-right: auto;
}

Minimum width is not globally supported, but can be implemented using

.divclass {
   min-width: 200px;
}

Then you can set your div to be

<div class="center divclass">stuff in here</div>
ck
no luck with 'minimum-width' in Firefox.
Casey
I think its called "min-width"
Richard Levasseur
updated to min-width
ck
+1  A: 
margin: 0 auto;

as ck has said, min-width is not supported by all browsers

Russ Cam
+1  A: 

minimal answer

stylesheet

div.mydiv {width: 200px; margin:0px auto}

html

<div class="mydiv">

I am in the middle

</div>

Your diagram shows a block level element also (which a div usually is), not an inline one.

of the top of my head, min-width is supported in ff2+/safari3+/ie7+. Can be done for ie6 using hackety css, or a simple bit of JS.

dysmsyd
Thanks for clarifying about the "inline" terminology. I was trying to say that I didn't want it to float over any text.
Casey
+6  A: 

In most browsers this will work...

Stylesheet

div.centre
{
  width: 200px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

HTML

<div class="centre">Some Text</div>

In IE6 you will need to add another outer div...

Stylesheet

div.layout
{
  text-align: center;
}
div.centre
{
  text-align: left;
  width: 200px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

HTML

<div class="layout">
  <div class="centre">Some Text</div>
</div>
Antony Scott
Yes, due to layout bugs in IE before IE7, you must do this. But in IE8, a simple text-align: centeris enough. :)
eriawan
That means IE8 is still wrong, as it isn't text.
ck
The first solution will work in IE6 if it isn't in quirks mode (activated with a comment/standard XML declaration as the first line of your XHTML document).
Tom
I've never actually tried that. So does the browser need to be in strict mode or is it just non-quirks?
Antony Scott
@Antony Scott: It needs to be in strict mode (has any doctype declared).
Tom
I think I'll have a play later on and try that out. Thanks Tom.
Antony Scott
@Antony - Check out http://quirksmode.org/ for browser compatibility info, hacks, workarounds, etc
Russ Cam