How can I let a div automatically set it own width?

后端 未结 4 1397
攒了一身酷
攒了一身酷 2021-02-04 10:35

How can I have a DIV\'s width behave like it does when float:left is set, but without setting a float? width:auto doesn\'t seem to do it (in chrome).

相关标签:
4条回答
  • 2021-02-04 10:41

    <div>s are block elements. They take the full width of their containers. Period. Just like <body> or <html>

    Your rule above is essentially doing this: div { width:100%; margin:0 auto; } as 100% is its auto value.

    inline-block would work, but it won't work exactly like a true inline-block element.

    Basically...you can't do it without setting a width, positioning it.

    If you go the inline-block route, give this a read...you may end up fighting some unexpected battles with your CSS expectations.

    http://www.brunildo.org/test/InlineBlockLayout.html (link found near the bottom of the following msdn page) http://msdn.microsoft.com/en-us/library/ms530751%28v=vs.85%29.aspx

    0 讨论(0)
  • 2021-02-04 10:50

    Solution with inline-block

    You could try display: inline-block and see if that works in your situation. However, you won't be able to center it using margin-left: auto & margin-right: auto because that technique requires a width value.

    If possible, use display: inline-block and set text-align: center on it's container.

    <div style="text-align: center">
      <div style="display: inline-block;">
         This will expand only as far as it needs to
      </div>
    </div>
    

    Solution using Flexbox + container div

    The original answer above was written in 2011, before flexbox was implemented. You can achieve a similar effect

    <div style="display: flex; justify-content: center;">
      <div>
         This will expand only as far as it needs to
      </div>
    </div>
    

    Solution without container div

    There is another way to do this without a parent element.

    1. Set display to inline-block to make the div width fit to its content.
    2. Use position: relative and left: 50% to position its left edge to 50% of its containing element.
    3. Use transform: translateX(-50%) which will "shift" the element to the left by half its own width.
    .center {
      display: inline-block;
      position: relative;
      left: 50%;
      transform: translateX(-50%);
    }
    
    0 讨论(0)
  • 2021-02-04 10:51

    For those of you who are still coming across this issue, nowadays you can handle this with:

    <div>
      <div style="display: table; margin: auto">
        This will expand only as far as it needs to
      </div>
    </div>
    

    Here is a new fiddle based on the accepted answer: http://jsfiddle.net/j33qL8pa/1/

    0 讨论(0)
  • 2021-02-04 10:54

    I think this works nowadays:

    .center
    {
        width: fit-content;
        margin-left: auto;
        margin-right: auto;
    }
    
    0 讨论(0)
提交回复
热议问题