How can I adjust DIV width to contents

前端 未结 5 1588
一向
一向 2021-01-31 14:59

I have a div element with style attached:

.mypost {
    border: 1px solid Peru;
    font-family: arial;
    margin: auto;
    min-width: 700px;
    width: 700px;         


        
相关标签:
5条回答
  • 2021-01-31 15:05

    Try width: max-content to adjust the width of the div by it's content.

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    div.ex1 {
      width:500px;
      margin: auto;
      border: 3px solid #73AD21;
    }
    
    div.ex2 {
      width: max-content;
      margin: auto;
      border: 3px solid #73AD21;
    }
    </style>
    </head>
    <body>
    
    <div class="ex1">This div element has width 500px;</div>
    <br>
    <div class="ex2">Width by content size</div>
    
    </body>
    </html>
    
    0 讨论(0)
  • 2021-01-31 15:06

    You could try using float:left; or display:inline-block;.

    Both of these will change the element's behaviour from defaulting to 100% width to defaulting to the natural width of its contents.

    However, note that they'll also both have an impact on the layout of the surrounding elements as well. I would suggest that inline-block will have less of an impact though, so probably best to try that first.

    0 讨论(0)
  • 2021-01-31 15:09

    EDIT2- Yea auto fills the DOM SOZ!

    #img_box{        
        width:90%;
        height:90%;
        min-width: 400px;
        min-height: 400px;
    }
    

    check out this fiddle

    http://jsfiddle.net/ppumkin/4qjXv/2/

    http://jsfiddle.net/ppumkin/4qjXv/3/

    and this page

    http://www.webmasterworld.com/css/3828593.htm

    Removed original answer because it was wrong.

    The width is ok- but the height resets to 0

    so

     min-height: 400px;
    
    0 讨论(0)
  • 2021-01-31 15:16

    I'd like to add to the other answers this pretty new solution:

    If you don't want the element to become inline-block, you can do this:

    .parent{
      width: min-content;
    }
    

    The support is increasing fast, so when edge decides to implement it, it will be really great: http://caniuse.com/#search=intrinsic

    0 讨论(0)
  • 2021-01-31 15:21

    One way you can achieve this is setting display: inline-block; on the div. It is by default a block element, which will always fill the width it can fill (unless specifying width of course).

    inline-block's only downside is that IE only supports it correctly from version 8. IE 6-7 only allows setting it on naturally inline elements, but there are hacks to solve this problem.

    There are other options you have, you can either float it, or set position: absolute on it, but these also have other effects on layout, you need to decide which one fits your situation better.

    • inline-block jsFiddle Demo
    0 讨论(0)
提交回复
热议问题