Search code examples
htmlcssimagelayoutmedia-queries

How to change the size of an image inside a div without changing the div size


learning CSS and using media queries. I have an image floated to the left and some text to the right of it.

<div id="imageContainer"><img  src="myImage.jpg" width="100%"></div>

<div id="someText"> some text....</div>

As I resize the browser's window, the image becomes smaller so a white gap starts appearing at the bottom. I want to fix this by increasing the size of the image using media queries. This is what I've tried:

@media screen and (min-width: 1000px) and (max-width: 1299px){
    #imageContainer img {min-width: 120%;}
}

This works as in the image starts to get smaller as the window resizes and when the width becomes smaller than 1299px the image increases in size making the gap disappear.

My problem is that as the image gets bigger so does the div that contains it, pushing the text to the right and ruining my layout. What I'd like is for the image to increase but for the containing div "imageContainer" to remain the same. I've looked into it and not too sure how to go about it. Thanks for your time.


Solution

  • Your issue is probably that the image is 120% size-- Meaning it'll be 120% the size of whatever its container is. Furthermore, your image and div are bonded. Or in other words, they both are relative position and thus bounce off each other. Try making your image be absolute position. It'll unbind it from the div while still being contained within it, if that makes sense.

    Do note that floats can't be applied to absolute positioned elements. Try wrapping your text to a particular width that'll work with the image's size.