Richard Fu
Richard Fu

Reputation: 626

Multiple images fill screen width using CSS

I have multiple images to show in a row that filled screen width:

<img src="1.jpg" style="max-width:25%">
<img src="2.jpg" style="max-width:25%">
<img src="3.jpg" style="max-width:25%">
<img src="4.jpg" style="max-width:25%">

In some pages I have 4 images but some have 5, 6, etc.

I don't want to change max-width for every pages so is that a way in CSS to take care of it?

p.s. I don't want to use table and background-image since a js plugin need find them as img, also img tag is google-friendly too...

Upvotes: 1

Views: 4335

Answers (2)

Jānis
Jānis

Reputation: 1812

I'd suggest you to use flexbox. It's really useful and can be mastered to make almost any kind of grid you want. Wrap all images in container class with display:flex and for each img element set flex:1. This is the simplest way. If you need to adjust it, read about it, it's great! Example here

.flexContainer {
  display:flex;
  max-height:200px;
  
}
.flexContainer > img {
flex:1;
border:1px solid;
margin:1px;
}
<div class="flexContainer">
<img src="http://lorempixel.com/image_output/food-q-c-640-480-5.jpg"/>
<img src="http://lorempixel.com/image_output/technics-q-c-640-480-10.jpg" />
<img src="http://lorempixel.com/image_output/food-q-c-640-480-3.jpg" />
<img src="http://lorempixel.com/image_output/food-q-c-640-480-5.jpg"/>
</div>
<br/>
<div class="flexContainer">
<img src="http://lorempixel.com/image_output/food-q-c-640-480-5.jpg"/>
<img src="http://lorempixel.com/image_output/technics-q-c-640-480-10.jpg" />
<img src="http://lorempixel.com/image_output/food-q-c-640-480-3.jpg" />
<img src="http://lorempixel.com/image_output/food-q-c-640-480-5.jpg"/>
<img src="http://lorempixel.com/image_output/technics-q-c-640-480-10.jpg" />
<img src="http://lorempixel.com/image_output/food-q-c-640-480-3.jpg" />
</div>

Upvotes: 2

Nazar Ilkiv
Nazar Ilkiv

Reputation: 68

There is no pure CSS way to solve it. Little jQuery can do it for you:

$(parentElem).each(function() {

    var itemsCount = $(this).children().length;
    var childrenWidth = 100 / itemsCount + '%';

    $(this).children().css('width', childrenWidth);

});

where parentElem is container for your images. jQuery each loop here in case you have multiple rows with images on your page.

Upvotes: 1

Related Questions