How can I make a div not larger than its contents?

前端 未结 30 3606
青春惊慌失措
青春惊慌失措 2020-11-21 07:35

I have a layout similar to:

I would like for the div to only exp

相关标签:
30条回答
  • 2020-11-21 07:55

    We can use any of the two ways on the div element:

    display: table;
    

    or,

    display: inline-block; 
    

    I prefer to use display: table;, because it handles, all extra spaces on its own. While display: inline-block needs some extra space fixing.

    0 讨论(0)
  • 2020-11-21 07:56
    width:1px;
    white-space: nowrap;
    

    works fine for me :)

    0 讨论(0)
  • 2020-11-21 07:58

    You can try this code. Follow the code in the CSS section.

    div {
      display: inline-block;
      padding: 2vw;
      background-color: green;
    }
    
    table {
      width: 70vw;
      background-color: white;
    }
    <div>
        <table border="colapsed">
          <tr>
            <td>Apple</td>
            <td>Banana</td>
            <td>Strawberry</td>
          </tr>
          <tr>
            <td>Apple</td>
            <td>Banana</td>
            <td>Strawberry</td>
          </tr>
          <tr>
            <td>Apple</td>
            <td>Banana</td>
            <td>Strawberry</td>
          </tr>
    
        </table>
    </div>

    0 讨论(0)
  • 2020-11-21 07:59

    There are two better solutions

    1. display: inline-block;

      OR

    2. display: table;

    Out of these two display:table; is better, because display: inline-block; adds an extra margin.

    For display:inline-block; you can use the negative margin method to fix the extra space

    0 讨论(0)
  • 2020-11-21 08:00

    You want a block element that has what CSS calls shrink-to-fit width and the spec does not provide a blessed way to get such a thing. In CSS2, shrink-to-fit is not a goal, but means to deal with a situation where browser "has to" get a width out of thin air. Those situations are:

    • float
    • absolutely positioned element
    • inline-block element
    • table element

    when there are no width specified. I heard they think of adding what you want in CSS3. For now, make do with one of the above.

    The decision not to expose the feature directly may seem strange, but there is a good reason. It is expensive. Shrink-to-fit means formatting at least twice: you cannot start formatting an element until you know its width, and you cannot calculate the width w/o going through entire content. Plus, one does not need shrink-to-fit element as often as one may think. Why do you need extra div around your table? Maybe table caption is all you need.

    0 讨论(0)
  • 2020-11-21 08:01

    display: inline-block adds an extra margin to your element.

    I would recommend this:

    #element {
        display: table; /* IE8+ and all other modern browsers */
    }
    

    Bonus: You can also now easily center that fancy new #element just by adding margin: 0 auto.

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