Nuthman
Nuthman

Reputation: 106

Evenly distribute items of uneven width across the entire width of a parent element in css

I've had difficulty figuring out how to cleanly do precicely what I am asking in the title.

Say for example I have a something like this:

<div class="image-row">
    <img src="image1">
    <img src="image2">
    <img src="image3">
    <img src="image4">
    <img src="image5">
</div>

I have seen answers to similar questions, but they don't deal with the issue of spreading mixed width elements across a responsive parent element.

In something like Photoshop, this is called "Distribute horizontal centers". Here is an example I made in photoshop (500px wide image-row):

enter image description here

here are the same boxes when image-row is stretched to 900px wide:

enter image description here

Note that the gaps between the images are not necessary even, the the spread is even based on the horizontal centers of the objects.

How can I accomplish this basic idea in css?

Upvotes: 0

Views: 697

Answers (3)

rby
rby

Reputation: 786

You can use a flex display and set justify-content to space-between. You can do that on your image-row class:

.image-row {
    display: flex;
    justify-content: space-between;
}

The point is to use this class on the container div.

Upvotes: 0

G-Cyrillus
G-Cyrillus

Reputation: 105883

You may use text-align:justify and a pseudo for older browser or use the display:flex properties for latest browsers.

.image-row {
  width: 500px;
  border: solid;
  margin: 1em auto;
}
img {
  vertical-align: top;
}
.justify {
  font-size: 0.01px;
  text-align: justify;
}
.justify:after {
  content: '';
  display: inline-block;
  width: 99%;
  vertical-align: top;
  height: 0;
}
.space-between {
  display: flex;
  justify-content: space-between
}
<div class="image-row justify">
  <img src="http://lorempixel.com/120/50">
  <img src="http://lorempixel.com/50/50">
  <img src="http://lorempixel.com/80/50">
  <img src="http://lorempixel.com/70/50">
  <img src="http://lorempixel.com/30/50">
</div>
<div class="image-row space-between">
  <img src="http://lorempixel.com/75/50">
  <img src="http://lorempixel.com/30/50">
  <img src="http://lorempixel.com/100/50">
  <img src="http://lorempixel.com/50/50">
  <img src="http://lorempixel.com/80/50">
</div>

Upvotes: 3

Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

Try this:

html

<div class="table">
    <div class="image-row">
        <div><img src="image1"></div>
        <div><img src="image2"></div>
        <div><img src="image3"></div>
        <div><img src="image4"></div>
        <div><img src="image5"></div>
    </div>
</div>

css

.table{
   display: table;
   width: 100%;
}
.image_row {
   diplay:table-row;

}
.image_row div {
   display: table-cell;
   text-align: center; /* if you want to be centered */
}
.image_row div img { 
   display:block; 
   max-width: 100%;  
}

Upvotes: 0

Related Questions