How to Center an Image with the CSS text-align Property
Solutions with HTML and CSS
In general, you cannot use the CSS text-align property to center an image, as it works only on block elements, and the <img> is an inline one. But there is a trick that will help you to center the image with the text-align property. If you need this property for some reasons, you can add a <div> element and specify the text-align property on it. Use the “center” value of this property.
Example of centering an image with the text-align property:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
border: 1px solid green;
text-align: center;
}
</style>
</head>
<body>
<h1>Example of centering an image </h1>
<div>
<img src="/uploads/media/default/0001/01/25acddb3da54207bc6beb5838f65f022feaa81d7.jpeg" alt="Aleq" width="200" height="185" />
</div>
</body>
</html>
Result
Example of centering an image
Let’s see another example, where the image is centered by applying a style immediately to the <img> element. In this case, you must set the display of the <img> to “block” and specify the margin property with "0 auto" as its value.
Example of centering an image:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
border: 1px solid green;
}
div img {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<h1>Example of centering an image</h1>
<div>
<img src="/uploads/media/default/0001/01/25acddb3da54207bc6beb5838f65f022feaa81d7.jpeg" alt="Aleq" width="200" height="185" />
</div>
</body>
</html>