As with many web design tasks, there’s more than one way to get this done! We’ll cover three major methods in this article. Let’s get started!
1. Use the margin Property
Setting the margin property is one of the easiest ways to horizontally center an image using CSS. Margins are a core component of the CSS box model.
First, you’ll need to transform the image element from an inline one to a block one. Block-level HTML elements occupy the full width of their parent element and are capable of taking up the entire width of a page.
By making an image element a block element, you can then manipulate its position by adjusting its horizontal margins. You’ll also need to set a specific width for the image, to determine just how much space the image takes up on the page.
Whatever width you choose, the image will need to have equal left and right margins. You can achieve this easily by giving the margin property a value of auto:
2. Use Flexbox Layout
This method requires putting the image in a block-level element, usually a div:
Once you’ve done this, you can add some properties to manipulate its appearance. You’ll use two CSS properties.
The first one is the display property with its value set to flex. You can also use flex to align elements in HTML. The second property you’ll add to your div is justify-content, with its value set to center like so:
3. Use the Deprecated center Element
Web best practices encourage you to use CSS for styling and HTML for semantics, so you shouldn’t use this HTML method. The center tag, which centers its contents horizontally, is deprecated in HTML5.
But if you must, here is how to center an image using HTML alone. Simply wrap the img tag in a center tag like so:
That’s How to Align Your Images in HTML
We’ve shown you three different, easy-to-use methods of centering your images in an HTML document. Try them all and choose the one that works best for you. Avoid the third method unless you have absolutely no choice!
One thing to keep in mind is that there are quite a few more ways to center images using HTML and CSS. One common method that works for both text and inline images is the text-align property.