treehouse : what would you like to learn today?
Web Design Web Development iOS Development

How to make a floated image act responsively?

  • <html>
    <head>
        <title>responsive images</title>
    </head>
    
    <body>
        <div class="container">
            <div id="text">This is some text this is some text this is some text</div>
            <img src="http://upload.wikimedia.org/wikipedia/en/thumb/5/5f/TomandJerryTitleCardc.jpg/250px-TomandJerryTitleCardc.jpg" width="294" height="225" class="frame" />
        </div>
    </body>
    </html>
    

    ​ and the css ---

    body { background: #dcdcdc; }
    img { max-width: 100%; height: auto; }
    
    .container { padding: 10px 12px; }
    #text{float:left; width:100px;margin-right:10px; }
    .frame {
        background: #fff;
        padding: 6px;
        box-shadow: 1px 1px 2px rgba(40, 40, 40, 0.8);
        -moz-box-shadow: 1px 1px 2px rgba(40, 40, 40, 0.8);
        -webkit-box-shadow: 1px 1px 2px rgba(40, 40, 40, 0.8);
    }
    

    My main concern in this fiddle is the div#text and img.frame. I'm trying to create a responsive website, but this has been my problem for so long, I can't figure out how 'to make the img behave beside the text and be responsive at the same time without going under the text when I try to reduce the size of the browser window. What it does is, it goes under the text before it acts responsively. Is there a workaround for this?

  • Hey, I've worked up a quick CodePen to give you some help.

    In my example, I floated the image, rather than the text. Then, by giving the image a width of 60%, the image will respond to the width of the browser. I've also done a media query for when the container gets too small to fit the image and the text nicely side by side. Hope it helps :)

  • Edit : ^^ what he said. ^^

  • Beat me too it. :P Done practically the same thing, except using columns. Basically by using percentages, when the browser beings to re size, it will respond to that exact percentage by the width of the browser at the time. @David_Leitch 's response is much better, as he uses a media query to proportionally scale everything neatly :)

    Pen Link

  • I've been cracking my head trying to figure this out for the past weeks. Thank you for that neat code @David_Leitch. Happy New Year everyone! :)

  • I know it's out of scope, and you want to learn which is good, but look at the thread too. You'll learn a lot from the frameworks provided in there if you look them up. All are responsive so it's a good learning curve if you want to practice your own responsive code! Which is the best Boilerplate?

    Happy New Year buddy!