Search code examples
htmlcssresponsive-designmedia-queries

Stacking a "float: right" div when window becomes narrow


This problem has been bugging me. I have two paragraphs of text and an image which relates to paragraph 1 floating in the top-right corner.

If the screen is wide, it should look like this where paragraph 1 and 2 are next to the image. (The image is a fixed size.)

https://i.sstatic.net/Qkjls.jpg

When the screen becomes narrow, I would like it stacked like this:

https://i.sstatic.net/KjU7C.jpg

This is what I have so far which doesn't stack correctly when the window is narrow. The image is stacked before paragraph 1, not after it.

<html>
<head>
    <style>
        #one { background-color: #CFF; }
        #two { background-color: #FCF; width: 400px; height: 300px; }
        #three { background-color: #FFC; }
        @media (min-width: 600px) {
            #two { float: right; }
        }
    </style>
</head>
<body>
    <div id="two">Image</div>
    <div id="one">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nisi augue, fringilla vel facilisis non, elementum pulvinar dolor. Fusce egestas suscipit dolor vitae tempus. In consectetur quam ante, vel pharetra diam pharetra id. Phasellus a volutpat justo. Suspendisse commodo tincidunt nunc, at ullamcorper massa auctor ac.</div>
    <div id="three">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nisi augue, fringilla vel facilisis non, elementum pulvinar dolor. Fusce egestas suscipit dolor vitae tempus. In consectetur quam ante, vel pharetra diam pharetra id. Phasellus a volutpat justo. Suspendisse commodo tincidunt nunc, at ullamcorper massa auctor ac.</div>
</body>
</html>

Solution

  • You can use the Display-Attribute. With table-xx-group you can control the position of e element.

    table-row-group:

    #one{
       display:table-row-group;
    }
    #content2{
        display:table-header-group;   
    }
    #content2 {
        display:table-footer-group;   
    }
    

    See Demo on js-fiddle.

    The values "table-column-group", "table-header-group" and "table-footer-group" are not supported in IE7 and earlier. IE8 requires a !DOCTYPE.