Label elements with fixed space (variable width)

I have a container with a variable number of elements in it. Elements should be justified, but with a fixed space between (e.g. 20px ). This means that the width of each element must adapt.

For instance:

HTML

 <div class="container"> <div> <img src="..."> </div> <div> <img src="..."> </div> <div> <img src="..."> </div> </div> 

CSS

 div.container { text-align: justify; } div.container div { display: inline-block; margin-right: 20px; } div.container div img { width: 100%; } 

At the end, it should look like this (in this figure two examples are shown: 2 elements and 3 elements, the width is dynamic, but the fix space [20px]):

picture showing elements

It should work with a different number of children .

Is there a professional way to do this using CSS?

EDIT : I have to mention that this fixed space is a% value!

+5
source share
2 answers

If you use Flexbox , you can add flex: 1 to the flex elements, as well as a fixed-value margin property as follows:

EXAMPLE HERE

 div.container { display: flex; } div.container div { height: 50px; /* Just for demo */ flex: 1; margin-left: 20px; } div.container :first-child { margin-left: 0; } 

Actually, flex: 1 is short for flex-grow: 1; in this case.

+4
source

You can use display: table and display: table-cell for this:

 .container { display: table; width: 100%; border-spacing: 10px 0; border-collapse: separate; background: palevioletred; } .container div { display: table-cell; } .container img { display: block; width: 100%; height: auto; } 
 <div class="container"> <div><img src="//dummyimage.com/200x100/000/CCC"></div> <div><img src="//dummyimage.com/300x100/000/CCC"></div> <div><img src="//dummyimage.com/400x100/000/CCC"></div> </div> <hr/> <div class="container"> <div><img src="//dummyimage.com/200x100/000/CCC"></div> <div><img src="//dummyimage.com/400x100/000/CCC"></div> </div> <hr/> <div class="container"> <div><img src="//dummyimage.com/600x100/000/CCC"></div> </div> 
+3
source

Source: https://habr.com/ru/post/1201409/


All Articles