Center multiple images horizontally with flexbox

The problem I'm having is when I add four images to the .images container, the justify-content:center property that I use to align the images horizontally on the page does not work.

However, when I have only two images inside the .images container, I get the images horizontally.

I was able to find a solution to center the images horizontally using the text-align property in the .images container. This is a bit like a hack.

CODE PEN

HTML

 <div class="proj_images"> <div class="images"> <img class="disp1" src="http://placehold.it/450x350.png" alt=""> <img class="disp2" src="http://placehold.it/450x350.png" alt=""> <img class="disp3" src="http://placehold.it/450x350.png" alt=""> <img class="disp4" src="http://placehold.it/450x350.png" alt=""> </div> </div> 

CSS

 .proj_images{ display: flex; width:100%; } .images{ text-align:center; } 
+5
source share
2 answers

Besides the solution you already have, you can also set the display of the .images element to flex , and then add justify-content: center along with flex-wrap: wrap .

When you set justify-content: center on the .proj_images element, it only centers the flexbox children (it will be .images , not the img child). That's why you will need to set these properties / values ​​for the direct parent of the img elements (so the img elements themselves are flexbox elements).

 .images { display: flex; justify-content: center; flex-wrap: wrap; } 
 <div class="proj_images"> <div class="images"> <img class="disp1" src="http://placehold.it/250x150.png" alt=""> <img class="disp2" src="http://placehold.it/250x150.png" alt=""> <img class="disp3" src="http://placehold.it/250x150.png" alt=""> <img class="disp4" src="http://placehold.it/250x150.png" alt=""> </div> </div> 
+3
source

When you create a flex container (by applying display: flex or display: inline-flex to an element), the child elements become flexible. The descendants of a flexible container outside of children do not become flexible elements and therefore do not accept flexible properties.

When you make a .proj_images flexible container, the flex properties apply to the unique flex: .images . To apply flexibility properties to four images, add display: flex to .images .

In addition, when you install the flex container, several default rules apply. Two of these rules are flex-direction: row and flex-wrap: nowrap . If you want the images to be aligned vertically or for wrapping, you need to override these defaults with flex-direction: column and flex-wrap: wrap .

For more information on centering flex elements horizontally (and vertically), see my answer here: fooobar.com/questions/1597 / ...

+3
source

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


All Articles