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

后端 未结 4 1483
攒了一身酷
攒了一身酷 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: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.

    This will expand only as far as it needs to

    Solution using Flexbox + container div

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

    This will expand only as far as it needs to

    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%);
    }
    

提交回复
热议问题