Center the content block when you don’t know its width in advance

After many attempts and searching, I never found a satisfactory way to do this with CSS2.

An easy way to do this is to turn it into a convenient <table> , as shown in the example below. Do you know how to do this by avoiding table layouts, as well as avoiding fancy tricks?

 table { margin: 0 auto; } 
 <table> <tr> <td>test<br/>test</td> </tr> </table> 

I want to know how to do this without a fixed width, and also be a block.

+6
html css
source share
6 answers

@Jason, yep, <center> works. Good times. I suggest the following:

 body { text-align: center; } .my-centered-content { margin: 0 auto; /* Centering */ display: inline; } 
 <div class="my-centered-content"> <p>test</p> <p>test</p> </div> 

EDIT @Santi, the block level element will fill the width of the parent container, so it will be effectively width:100% , and the text will flow to the left, leaving you useless markup and an off-center element. You might want to try display: inline-block; . Firefox may complain, but right . Also, try adding border: solid red 1px; in the CSS .my-centered-content DIV to find out what happens when you try this.

+9
source share

This will be the easiest answer, but it works:

Use the obsolete <center> tag .

: R

I said it would be lame. But, as I said, it works!

* Shiver *

+4
source share

I think your example will work just as well if you used a <div> instead of a table <. The only difference is that the text in the table> is also focused. If you want this too, just add text-align: center; The rule.

Another thing to keep in mind is that a <div> will fill all available horizontal spaces by default. Put a border on it if you don’t know where it starts and ends.

+1
source share

The following works quite well. pay attention to the position and use of the car

 <div style="border: 1px solid black; width: 300px; height: 300px;"> <div style="width: 150px; height: 150px; background-color: blue; position: relative; left: auto; right: auto; margin-right: auto; margin-left: auto;"> </div> </div> 

NOTE: not sure if it works in IE.

0
source share

 #wrapper { width: 100%; border: 1px solid #333; } #content { width: 200px; background: #0f0; } 
 <div id="wrapper" align="center"> <div id="content" align="left"> Content Here </div> </div> 
0
source share

In FF3 you can:

 <div style="display: table; margin: 0px auto 0 auto;">test<br>test</div> 

This has the advantage that any element makes the most sense (replace the div with something better if necessary), but the drawback that it fails in IE (grr ...)

In addition, without setting the width, it is best to use javascript to accurately position the left edge. I'm not sure if you would classify this as a "bizarre trick."

It really depends on what you want to do, of course. Given your simple test case, a div with text-align: center will have exactly the same effect.

0
source share

All Articles