Loading lesson path
With CSS, you can center images with several methods. An image can be centered horizontally, vertically, or both.
To display a horizontally centered image, we can use margin: auto;
or display: flex;.Horizontally centered image using margin: auto:
img {
display: block;
margin: auto;
width: 50%;
}Formula
Here, we put the < img > element inside a < div > container.We add the following CSS to the div container:
Formula
display: flex justify - content: center(centers the image horizontally in the div container) Then, we set a width for the image. The width of the image must be smaller than the width of the page. Here is a horizontally centered image using display: flex
Horizontally centered image using display: flex:
div {
display: flex;
justify-content: center;
}
img {
width: 50%;
}To display an image that is both vertically and horizontally centered (true centering), we can use display: flex; or display:
grid;.display: flex;
justify-content: center;
(centers the image horizontally in the container)
align-items: center;
(centers the image vertically in the container)
height: 600px;
(the height of the container)Formula
Here, we also put the < img > element inside a < div > container.
Then, we set a width for the image (must be smaller than the width of the container).Here is a vertically and horizontally centered image with flexbox:
div {
display: flex;
justify-content: center;
align-items: center;
height: 600px;
border: 1px solid black;
}
img {
width: 50%;
}display: grid;
place-items: center;
(centers the image horizontally and vertically in the container)
height: 600px;
(the height of the container)Formula
Here, we also put the < img > element inside a < div > container.
Then, we set a width for the image (must be smaller than the width of the container).Here is a vertically and horizontally centered image with grid:
div {
display: grid;
place-items: center;height:
600px;
border: 1px solid black;
}
img {
width: 50%;
}