Search code examples
htmlcssimageformattinginline

How do I keep my image from overflowing an inline-block container


I have a website I am putting together for a client. Everything was going swimmingly until I ran into what seems like a simple problem, but one that I have never had to deal with before and can't find a solution to.

I'm trying to set up a 2 column deal with a heading and text on one side and an image on the other. I have my image and my text inside respective container divs. The divs have their display set to "inline-block" and thus, the image won't scale down to fit inside it's div. Is there a simple solution to this?

Here is the code:

HTML

<div class="col">
    <h1>Header</h1>
    <p>Text</p>
</div>
<div class="col">
    <img src="images/img1.jpg" alt="Image">
</div>

CSS

.col {
    display: inline-block;
    width: 45%;
    vertical-align: top;
    margin-bottom: 20px;
}

Again, I know this is probably super easy (or completely impossible for some reason) but any help would be appreciated.


Solution

  • Simply add width: 100% to the CSS.

    .col img {
      width: 100%;
    }
    

    Or you can put it in the <img> tag:

    <div class="col">
        <img src="images/img1.jpg" alt="Image" width="100%">
    </div>
    

    The image will grow proportionally to the maximum width of the parent element. If you don't explicitly set the width, it will be presented in its original size.