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

后端 未结 9 1484
感情败类
感情败类 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 18:53
    <div style="width: auto; margin-left: auto; margin-right: auto">
     div content
    </div>
    

    will align center on the page

    0 讨论(0)
  • 2021-02-09 18:59

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

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

    here a nice workaround for centering a div with no width:

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

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

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

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

    P.S. You can have a div to shrink dynamically as well by setting the float property to float:left or float:right. So it will stick to the left or the right, but you can't have it centered this way.

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

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

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

    the div element will take all the width space of the container element if it isn't set a width value.

    So if you want to center a div you must set a width...

    A solution to your problem (if I have understand it) can be:

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

    where your div has became a span and a new div puts the span in the center. Hope this can help you! Bye, Alberto

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