pexichdu pexichdu - 4 months ago 8
CSS Question

Make image fit in container

I'm trying to use bootstrap grid system with rows each has 4 column contains image, but the image size is big and it gets over its container, so I set image position : absolute and div position: relative but it still doesn't work. Is there any way to make the image fit the div container with containers's size?

HTML:

<div class="container">
<div class="row">
<div class="col-md-3 sec5row">
<img class="filter" src="resources/images/f1.jpg" alt="f1">
</div>
<div class="col-md-3 sec5row">
<img class="filter" src="resources/images/f2.jpg" alt="f1">
</div>
<div class="col-md-3 sec5row">
<img class="filter" src="resources/images/f3.jpg" alt="f1">
</div>
<div class="col-md-3 sec5row">
<img class="filter" src="resources/images/f4.jpg" alt="f1">
</div>
</div>
<div>


CSS:

.sec5row {
border : 1px solid red;
position: relative;
}
.filter {
position: absolute;
}

Answer

I think the bootstrap class ".img-responsive" solves your problem. So try something like this:

<div class="container">
        <div class="row">
            <div class="col-md-3">
                <img class="img-fluid" src="resources/images/f1.jpg" alt="f1">
            </div>
            <div class="col-md-3">
                <img class="img-fluid" src="resources/images/f2.jpg" alt="f1">
            </div>
            <div class="col-md-3">
                <img class="img-fluid" src="resources/images/f3.jpg" alt="f1">
            </div>
            <div class="col-md-3">
                <img class="img-fluid" src="resources/images/f4.jpg" alt="f1">
            </div>
     </div>
 <div>

It sets the style of your image to "max-width: 100%;" and "height: auto;" which should be exactly what you need. There should be no need for any additional css.

Comments