How can I center alignment without knowing the width?

I looked at it, and the look seems bleak. I'm not interested in using a table. I have 6 or so “built-in blocks” of elements that make up the menu. It slides, except that all elements "a" are set to width: auto; to place their text. Without explicit width, I cannot center their alignment. I have a container div and a child div that wraps my “elements”.

Any thoughts? thanks Mike

+6
javascript html css
source share
9 answers

You can set a style to margin: 0 auto , but this does not work in IE6. In IE6, you must set the text-align: center div wrapper and (optionally) set the text alignment for element a back to text- align: left

+7
source share
<div style="width: auto; margin-left: auto; margin-right: auto"> div content </div> 

center the page

+2
source share

the div element will take the entire width space of the container element if it is not set for the width value.

So, if you want to center the div, you have to set the width ...

The solution to your problem (if I understand it) could be:

 <div style="text-align:center;"><span>[... yours content ...]</span></div> 

where your div became the span and the new div puts the span in the center. Hope this helps you! Goodbye Alberto

+1
source share

My advice is the answer, however someone commented that it would not work in IE6. Here's how to do it:

 <div id="container"> <div id="centeredBlock">centered</div> </div> #container { text-align: center; } #centeredBlock { margin: 0 auto; text-align: left; width: 50%; } 
+1
source share

You need to set margin: 0 auto; to the outer container div, add text-align: center; in the inner div; and use the unordered list to create your menu first.

0
source share

Without setting an explicit width, the <div> will automatically expand to 100% of its parent's width. Therefore, setting margin: 0 auto; will make it the center - with 0px both on the left and on the right.

0
source share

here is a good workaround for centering a div without width:

http://www.kensfi.com/how-to-align-center-a-div-with-no-width-declared/

0
source share

Here is also a good example of the situation: http://www.cssplay.co.uk/menus/centered.html

0
source share

If you need it to be centered and dynamically contracted / expanded to accommodate content without knowing the width, then your only option is really using a table. This is the only elastic element in the HTML repertoire.

 <table style="margin-left:auto;margin-right:auto;"> <tr> <td> Whatever... </td> </tr> </table> 

PS You also have the option of dynamically reducing the div by setting the float property float: left or float: right. Therefore, he will stick to the left or right, but you cannot concentrate him that way.

-one
source share

All Articles