开发者

How to have a box increase its size based on its content?

Consider a page (full source below) where you have:

  • A containing div, styled so its border is visible.
  • A contained box, which content can't be made smaller than a certain width. Here we'll use an image for this.

This renders as follows, and as expected the div "contains" the image:

How to have a box increase its size based on its content?

However, if you make the browser window smaller, you get to a point where it is not large enough for the image: part of the image won't be visible, and the browser needs to add a scrollbar. So far so good. However, the div size is still based on the viewport width, and consequently the image gets outside of the div:

How to have a box increase its size based on its content?

Instead, I would like to have the div always be "around" the image, and become wider if containing box can't be made narrower. Interestingly, this is exactly what happens in Quirks mode, here a开发者_如何学Gos rendered by IE8:

How to have a box increase its size based on its content?

How can I get, by adding CSS, the exact same result I get in Quirks with IE8, but in standards mode? And for reference, here is the full source of this example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <style type="text/css">
            /* Styling */
            div     { background-color: #999 }
            body    { font-family: sans-serif }
            div     { margin: .5em 1em; padding: .5em }
        </style>
    </head>
    <body>
        <div>
            <img src="http://placekitten.com/g/400/100"/>
        </div>
    </body>
</html>


Try this:

CSS:

Old answer, Truncated

HTML:

Old answer, Truncated

Demo


EDIT:

After much tinkering, this is what i could come up with:

CSS:

.table {
    display:table;
    background-color: #999;
    width:90%;
}

.row {
    display:table-row;
}

.cell {
    display:table-cell;
    margin: .5em 1em;
    padding: .5em
}

HTML:

<div class="table">    
    <div class="row">
        <div class="cell">
            <img src="http://placekitten.com/g/400/100"/>
        </div>
    </div>
</div>

Accompanying fiddle: http://fiddle.jshell.net/andresilich/Q4VnF/


I'd go for div { display: table-cell; }

EDIT: I don't think this can be done with the markup as given. You can get close using div { display: table; width: 100%; } but it doesn't like having a margin. If you use two block elements then you can put { display: table; width: 100%; } on the outer element and { display: table-cell; } and the margin, padding and background on the inner element.


With display: inline-block it also works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜