Search code examples
htmlcssquirks-mode

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:

div contains image

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:

div narrower than image

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 as rendered by IE8:

quirks mode

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>

Solution

  • 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/