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

前端 未结 30 3659
青春惊慌失措
青春惊慌失措 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:10

    The answer for your question lays in the future my friend ...

    namely "intrinsic" is coming with the latest CSS3 update

    width: intrinsic;
    

    unfortunately IE is behind with it so it doesn't support it yet

    More about it: CSS Intrinsic & Extrinsic Sizing Module Level 3 and Can I Use?: Intrinsic & Extrinsic Sizing.

    For now you have to be satisfied with <span> or <div> set to

    display: inline-block;
    
    0 讨论(0)
  • 2020-11-21 08:11

    I think using

    display: inline-block;
    

    would work, however I'm not sure about the browser compatibility.


    Another solution would be to wrap your div in another div (if you want to maintain the block behavior):

    HTML:

    <div>
        <div class="yourdiv">
            content
        </div>
    </div>
    

    CSS:

    .yourdiv
    {
        display: inline;
    }
    
    0 讨论(0)
  • 2020-11-21 08:11

    Not knowing in what context this will appear, but I believe the CSS-style property float either left or right will have this effect. On the other hand, it'll have other side effects as well, such as allowing text to float around it.

    Please correct me if I'm wrong though, I'm not 100% sure, and currently can't test it myself.

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

    You can use inline-block as @user473598, but beware of older browsers..

    /* Your're working with */
    display: inline-block;
    
    /* For IE 7 */
    zoom: 1;
    *display: inline;
    
    /* For Mozilla Firefox < 3.0 */
    display:-moz-inline-stack;
    

    Mozilla doesn’t support inline-block at all, but they have -moz-inline-stack which is about the same

    Some cross-browser around inline-block display attribute: https://css-tricks.com/snippets/css/cross-browser-inline-block/

    You can see some tests with this attribute in: https://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

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

    Revised (works if you have multiple children): You can use jQuery (Look at the JSFiddle link)

    var d= $('div');
    var w;
    
    
    d.children().each(function(){
     w = w + $(this).outerWidth();
     d.css('width', w + 'px')
    });
    

    Do not forget to include the jQuery...

    See the JSfiddle here

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

    You can do it simply by using display: inline; (or white-space: nowrap;).

    I hope you find this useful.

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