+3 votes
88 views
in Tips & Tricks by (242k points)
reopened
CSS: center image

1 Answer

+4 votes
by (1.6m points)
 
Best answer

How to center an image horizontally in CSS
How to center an image vertically in CSS

Centering an image in CSS is not entirely trivial. We'll explain to you how you can cope with the task anyway..

image image

In this tipps + tricks article, we explain the most common methods of centering an image both vertically and horizontally using different CSS properties. Read everything you need to know below.

How to center an image horizontally in CSS

We have put together three options for you to use CSS to center the image on your website:

Margin: Auto

The first way to make an image horizontal is to use margin: auto . This sets the left-margin and right-margin properties to automatic and helps with centering. However, its use does not work automatically for images, since these are inline elements. With the help of the command display: block in the CSS code, images can easily be converted into block elements. Then the automatic alignment also works.

You also have to define a width for the image - which is accordingly not 100% - so that the image can automatically align itself based on the left and right edges..

We have created sample code for you using the online editor at w3schools.com . Click "Run" on the linked page. Then the specified CSS style is used to specify that the image is output centered.

Text Align

The second way to horizontally center an image is to use the text-align property . However, this method only works if the image is in a block container such as <div>..

Here, too, we have created an example for you to try out on w3school.com . Simply click on "Run" again to try it out.

Display: Flex

The third way to center an image horizontally is by using display: flex . Analogous to text-align , the properties for a container such as div must also be redefined for display: flex . In addition, the property justify-content: center must be defined. Finally, the width of the image must be smaller than the width of the container, otherwise it will take up 100% of the space and therefore cannot be centered.

The whole thing can again be viewed as an example for you on w3school.com in the editor with a preview function .

How to center an image vertically in CSS

An image can also be centered vertically using CSS. The use of display: flex is also possible here. For example, you have an element that is 1000px high and an image that is only 600px high. To align the image vertically, you need to add the line of code align-items: center in CSS . Overall, the centering looks like this:


...