how to align multiple images in html horizontally
When we are coding or designing any web page we need to align text. And in CSS language there is a very easy solution to align text. Just add “
text-align: right | left | center” and you are done. But sometimes you need to align multiple div, objects or images horizontally.
Now what will you do? How will you align these images, objects or divs horizontally? Here I shall teach you how to align multiple images in html horizontally using CSS.
Step 1 – Create an Empty HTML Document
First of all create an empty html document as shown below in screen shot.
Step 2 – Add Images in the HTML Document
Now we have successfully created our web page. Let’s add the images to our document.
In the above screenshot you will see that I have created a div that has the class of “
images-container”. And inside that div I have added three images. Now let’s render this web page in our web browser to see how the images look like.
In the above screenshot you will see our images are shown left aligned next to each other. Now let’s align our images center horizontally.
Step 3 – Align Images Horizontally Using Flex-box
Flex-box is very useful when you want to align items.
In the above screenshot you will see I have written some CSS. Now let’s describe the CSS first then we shall render our webpage into a web browser to see our images.
At line #10 you will see I have used class “images-container” and written these properties:
display: flex” changes the display behavior of the parent to flex. Then we have added another property right below to display, that is “
justify-content: center”. This property horizontally center aligns all images.
And finally I have added the margin to the left and right side of each image to show some margins to left and right to them. Now let’s see the result in our web browser.
You will see our all three images are horizontally center aligned. But there is an issue that our all images are now equal sized. That means our images are stretched according to the height of our big image. This is an issue. See the two images below and you will see the difference.
In the above screenshot you can see the difference. Now let’s fix this issue by adding an additional property.
Now you can see in the above screenshot I have added one extra property that is “
align-items: center”. Now let’s render the web page and see it in the web browser.
Now our images are center aligned horizontally and center according to the items vertically.
You will see in the code that I have also added additional properties, which are commented.If you want to align all items vertically you can use the “
align-items: flex-start” property or if you want to align items bottom then use “