Min-width, max-width css use smallest width

前端 未结 3 1898
野的像风
野的像风 2021-01-05 05:26

Alright, so what I\'m hoping to do is to create a DIV that will autosize based on the content that\'s in it, but it should use the smallest width possible. I haven\'t a clue

相关标签:
3条回答
  • 2021-01-05 06:11

    The issue is that since <div>s are block-level elements, they do not auto-resize to fit their content, although their width can be explicitly defined. Inline elements like <span> do auto-size to fit their content, but they don't accept defining their width through CSS. The workaround is to make your <div> behave somehow like a table cell. Here's an example:

    CSS:

    .widthlim {
        min-width: 200px;
        max-width: 1000px;
        background-color: red; /*This is just for us to be able to see the width*/
        display: table-cell;
        word-wrap: break-word;
        word-break: break-word;
    }
    

    HTML:

    Example 1:<br/>
    <div class = "widthlim">
    Hello
    </div>
    Example 2:<br/>
    <div class = "widthlim">
    Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
    </div>
    Example 3:<br/>
    <div class = "widthlim">
    Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello 
    </div>
    

    (Note how we had to add <br/>s before the <div>s because they're no longer completely block-level).
    Here's how that looks when rendered: The above example rendered This seems to work on Firefox, Chrome, and IE8 (for IE8 you need to specify a DOCTYPE). I hope that helped!

    0 讨论(0)
  • 2021-01-05 06:22

    If I understood what you're asking about correctly, <div>s are block-elements, which means that by default they'll take a up a whole line -- 100% of the screen width. Try using the <span> element instead.

    Hope that helped, but we can help you more if you specify what behavior you're trying to do or achieve.

    0 讨论(0)
  • 2021-01-05 06:23

    You can "shrink-wrap" a div in a few different ways. The easiest is probably to display: inline; but a float will behave like you describe as well.

    Check out http://haslayout.net/css-tuts/CSS-Shrink-Wrap for details and more methods.

    If you want the minimum width to be 200px (contradictory to your first paragraph) you can use min-width: 200px; along with display: inline-block for instance.

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