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

后端 未结 9 1485
感情败类
感情败类 2021-02-09 18:45

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 t

相关标签:
9条回答
  • 2021-02-09 19:08

    My advice is this answer - however someone commented that it wouldn't work in IE6. Here's how to make this work:

    <div id="container">
        <div id="centeredBlock">centered</div>
    </div>
    
    #container {
        text-align: center;
    }
    
    #centeredBlock {
        margin: 0 auto;
        text-align: left;
        width: 50%;
    }
    
    0 讨论(0)
  • 2021-02-09 19:08

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

    0 讨论(0)
  • 2021-02-09 19:15

    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

    0 讨论(0)
提交回复
热议问题