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

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

I have a layout similar to:

I would like for the div to only exp

相关标签:
30条回答
  • 2020-11-21 08:02

    This has been mentioned in comments and is hard to find in one of the answers so:

    If you are using display: flex for whatever reason, you can instead use:

    div {
        display: inline-flex;
    }
    

    This is also widely supported across browsers.

    0 讨论(0)
  • 2020-11-21 08:02
    div{
      width:auto;
      height:auto;
    }
    
    0 讨论(0)
  • 2020-11-21 08:03

    What works for me is:

    display: table;
    

    in the div. (Tested on Firefox and Google Chrome).

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

    Just put a style into your CSS file

    div { 
        width: fit-content; 
    }
    
    0 讨论(0)
  • 2020-11-21 08:04
    display: -moz-inline-stack;
    display: inline-block;
    zoom: 1;
    *display: inline;
    

    Foo Hack – Cross Browser Support for inline-block Styling (2007-11-19).

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

    My CSS3 flexbox solution in two flavors: The one on top behaves like a span and the one at the bottom behaves like a div, taking all the width with the help of a wrapper. Their classes are "top", "bottom" and "bottomwrapper" respectively.

    body {
        font-family: sans-serif;
    }
    .top {
        display: -webkit-inline-flex;
        display: inline-flex;
    }
    .top, .bottom {
        background-color: #3F3;
        border: 2px solid #FA6;
    }
    /* bottomwrapper will take the rest of the width */
    .bottomwrapper {
        display: -webkit-flex;
        display: flex;
    }
    table {
        border-collapse: collapse;
    }
    table, th, td {
        width: 280px;
        border: 1px solid #666;
    }
    th {
        background-color: #282;
        color: #FFF;
    }
    td {
        color: #444;
    }
    th, td {
        padding: 0 4px 0 4px;
    }
    Is this
    <div class="top">
    	<table>
            <tr>
                <th>OS</th>
                <th>Version</th> 
            </tr>
            <tr>
                <td>OpenBSD</td>
                <td>5.7</td> 
            </tr>
            <tr>
                <td>Windows</td>
                <td>Please upgrade to 10!</td> 
            </tr>
        </table>
    </div>
    what you are looking for?
    <br>
    Or may be...
    <div class="bottomwrapper">
        <div class="bottom">
        	<table>
                <tr>
                    <th>OS</th>
                    <th>Version</th> 
                </tr>
                <tr>
                    <td>OpenBSD</td>
                    <td>5.7</td> 
                </tr>
                <tr>
                    <td>Windows</td>
                    <td>Please upgrade to 10!</td> 
                </tr>
            </table>
        </div>
    </div>
    this is what you are looking for.

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