Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I center align a div without knowing the width?

I've looked this up and the outlook seems bleak. I'm not interested in using a table. I have 6 or so 'a element' inline-blocks that make up a menu. It's slick, except all the 'a elements' are set to width: auto; to accommodate their text. Without an explicit width, I'm not able to center align them. I have a container div and a child div that wraps around my 'a elements'.

Any thoughts? Thanks Mike

like image 510
Michael Swarts Avatar asked Jul 14 '09 07:07

Michael Swarts


People also ask

How do I center a div without the width?

Using the Position, Top, Left, and Transform Properties To horizontally and vertically center a div within a div whose height and width is unknown, you can use the transform property instead of the margin property. You'll still use the CSS position, top, and left properties.

How do I center a div without margin auto?

Div is basically BLOCK with FULL-WIDTH (100%) so set margin:auto is doesn't get anything since the width is full to the parent. To make it work, you can did that by 2 ways, use text-align:center for div -> this will align text inside div center. include width property in div (i.e. width:200px) and it will work fine.

How do I force a div to center?

Simply add text-align center to parent div and set the child div display to inline-block. This will force our div to behave like inline element and therefore subjected text-align center.

How do I center a div according to my screen size?

Easiest way to center something regardless of page width is margin: auto; in your CSS, with height and width defined. Save this answer.


2 Answers

You could set the style of the a element to margin: 0 auto, but that doesn't work in IE6. In IE6, you should set the wrapper div to text-align: center, and (optionally) set the text-alignment for the a element back to text-align: left

like image 184
Philippe Leybaert Avatar answered Sep 19 '22 10:09

Philippe Leybaert


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

will align center on the page

like image 45
Sergei Kovalenko Avatar answered Sep 20 '22 10:09

Sergei Kovalenko