CSS allows us to manage the presentation of images within web applications. Aligning images or text at the center is a frequent requirement in CSS. To center an image, it is necessary to assign the margin-left and margin-right properties a value of auto and convert it into a block element by utilizing the display: block; attribute.
If the image is contained within a div element, the text-align: center; CSS property can be employed to center-align the image within the div.
The <img> tag is considered an inline element that can be conveniently aligned at the center by using the text-align: center; CSS property on the containing parent element.
Note: The image cannot be centered if the width is set to 100% (full-width).
We have the option to utilize the shorthand property margin and assign it the value auto to center align the image, instead of relying on the margin-left and margin-right properties.
Let's explore how to align an image at the center by utilizing the text-align: center; CSS property on its containing element.
Example
In this instance, we are centering the images by applying the text-align: center; attribute. The image is contained within a div element.
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 2px solid red;
}
img{
height: 300px;
width: 300px;
}
#center {
text-align: center;
}
</style>
</head>
<body>
<div id ="center">
<img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image">
</div>
</body>
</html>
Output
Example
Now, we utilize the margin-left: auto; margin-right: auto; and display: block; CSS properties to center-align the image.
<!DOCTYPE html>
<html>
<head>
<style>
body{
background-color: lightblue;
}
#image {
display: block;
margin-left: auto;
margin-right: auto;
border: 8px ridge blue;
padding: 5px;
}
</style>
</head>
<body>
<img src = "https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" id ="image" width="300" height="300">
</body>
</html>
Output