To center an image in CSS, several steps can be taken. Depending on the desired outcome, different approaches can be used. Here, we will discuss two commonly used methods.
margin
propertyWe can center an image horizontally by using the margin
property.
Line 2: We set display: block
to make the image a block-level element, which allows us to center it horizontally using margin
.
Line 3: We set margin: auto
to set the left and right margins to auto
, which centers the image horizontally.
Note: This code will center the image horizontally. To center it vertically as well, we’ll need to add a few more CSS properties.
To center the image vertically, we’ll add a few more CSS properties. We will use the flexbox layout. Here’s an example:
Line 1: The .container
parent element contains the image.
Line 2: We set display: flex
to create a flex container, which allows us to align items easily.
Line 3: We set justify-content: center
to center the image horizontally.
Line 4: We set align-items: center
to center the image vertically.
Line 5: We set height: 100vh
to set the height of the container to the viewport height, which makes the container to take up 100% of the vertical height of the screen. If, instead, we set the height to 10vh, the container would take up only 10% of the viewport height.
Lines 9–10: We set max-width: 100%
and max-height: 100%
to ensure that the image does not exceed the size of the container.
Free Resources