简体   繁体   中英

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):

在此处输入图片说明

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

在此处输入图片说明

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?

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> 

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%;  
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM