Image centering or alignment is a useful technique for achieving appealing layouts in web development. Centering an image has different advantages, such as ensuring consistency across different screen sizes and devices for a uniform user experience, maintaining visual balance, and making images a focal point of the layout.
In this tutorial, we’ll walk you through how you can use HTML and CSS to center images in your own projects using different techniques.
In this article:
- Block vs. Inline HTML Elements
- Center Images using text-align
- Centering Images with Flexbox
- Centering Images with CSS Grid
Block vs. Inline HTML elements
Before we dive into how to center images with HTML and CSS, it’s important we first understand why images can be hard to center in a layout flow, especially for beginners who do not have an advanced understanding of CSS.
The essential thing to remember when working with HTML and CSS is the behavior of block and inline HTML elements in a layout flow. Let’s break this down.
Block Elements
HTML block elements are laid out one after the other, either vertically or horizontally, depending on the writing mode used. For example, block elements will be stacked vertically or top-to-bottom in a horizontal writing mode, such as in English. Conversely, block elements would be laid out horizontally in a vertical writing mode.
In other words, block-level elements typically start on a new line and occupy the full width available to them in a given layout or container. Examples of block elements include <div>
, <p>
, <h1> - <h6>
, <ul>
, <ol>
, <li>
, <table>
, <form>
, etc.
In the diagram below, we can see the texts laid out vertically, ignoring the spaces on their right side:
Inline Elements
Inline elements display one after the other in the direction that sentences run in that particular writing mode. For example, in a horizontal writing mode such as English, inline elements will be laid out horizontally, and vice versa.
In other words, inline elements do not start on a new line and only take up as much width as their content requires. Examples of these elements include, <span>
, <a>
, <img>
, <input>
, <button>
, <label>
, etc.
In the example below, the buttons are arranged in a horizontal line to fill up the spaces to the right:
Now that we know the HTML img
element is an inline element, let’s look at some examples.
Center Images Using text-align
When you’re working with a very basic layout, the simplest way to align an image in the center of its parent container is to use the text-align: center
CSS declaration on the parent element. Below is an example code showing this in action:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .container { width: 100%; text-align: center; } </style> </head> <body> <section class="container"> <div class="heading-wrapper"> <div class="heading"> <h2 class="heading-text">Centering images with HTML and CSS</h2> </div> </div> <div class="image-wrapper"> <div class="image"> <img height="100%" width="50%" src="https://images.unsplash.com/photo-1714745455353-f47a2e2b5647?q=80&w=2070&auto=format&fit=crop" alt="a-man-in-a-black-hat-is-standing-in-the-middle-of-the-street" /> </div> </div> <div class="text-wrapper"> <div class="text"> <p class="text-1"></p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis alias ratione repudiandae adipisci quaerat, e consequuntur maxime veniam et corrupti aliquam sunt nulla! Error iste velit minima a odio omnis? Repudiandae. </div> </div> </section> </body> </html>
Here’s the output:
When using images in web development, it’s a good practice to always set their width and height to prevent layout shifts that may negatively impact user experience. Barry Pollard wrote this great article on setting image width and height properties.
Center images with Flexbox
In CSS, Flexbox is a one-dimensional layout method for arranging items in rows or columns. Using Flexbox, we can easily control whether to align an image vertically or horizontally. The following are the CSS properties and declarations we’ll be looking at in this section.
display: flex
: This creates a flex container, which enables a Flexbox layout.justify-content
: This controls the alignment of all items along the main axis of a flex container.align-items
: This specifies how flex items are aligned along the cross-axis of the flex container.flex-direction
: This gives the direction in which flex items are placed within the flex container. It allows us to arrange items horizontally (flex-direction: row
) or vertically (flex-direction: column
) or in reverse for either direction.
Center Images Horizontally with Flexbox
By default, the display: flex
declaration aligns flexbox items in a horizontal plane (row), so we don’t have to use the flex-direction: row
declaration here. Below’s the code from before, modified to show how this works:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .container { width: 100%; display: flex; align-items: center; justify-content: center; } .container > div { flex: 200px; margin-inline: 15px; } </style> </head> <body> <section class="container"> <div class="heading-wrapper"> <div class="heading"> <h2 class="heading-text">Centering images with HTML and CSS</h2> </div> </div> <div class="image-wrapper"> <img class="image" height="100%" width="100%" src="https://images.unsplash.com/photo-1714745455353-f47a2e2b5647?q=80&w=2070&auto=format&fit=crop" alt="a-man-in-a-black-hat-is-standing-in-the-middle-of-the-street" /> </div> <div class="text-wrapper"> <div class="text"> <p class="text-1"></p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis alias ratione repudiandae adipisci quaerat, e consequuntur maxime veniam et corrupti aliquam sunt nulla! Error iste velit minima a odio omnis? Repudiandae. </div> </div> </section> </body> </html>
In the above code, the flex: 200px
declaration set on the three flex items means each will be at least 200px wide. However, feel free to customize this value depending on your use cases.
Here’s the output:
Centering Images Vertically with Flexbox
The .container
class is set as a flex container with display: flex
. This applies flexbox properties to its direct children, including .heading-wrapper
, .image-wrapper
, and .text-wrapper
. However, the .image-wrapper
is not centered by default because it contains an inline element. Using the same code from before, by adding the following declaration to .image-wrapper
and .container
, we can align the image vertically:
/* ... */ <style> .container { width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; } .image-wrapper{ justify-content: center; display: flex; } </style> /* ... */
Here’s the result:
Center Images with CSS Grid
A grid is a two-dimensional layout with a set of intersecting horizontal and vertical lines defining columns and rows. It provides precise control over the placement and alignment of elements within the grid, making it a great tool for creating complex and responsive layouts.
Center Images Horizontally with a Grid
To center an image horizontally with a CSS grid, change the code from before to the following:
<style> .container { width: 100%; display: grid; grid-template-columns: 1fr 1fr 1fr; align-items: center; justify-content: center; } </style>
Here’s how the code works:
display: grid
: This sets up the container as a grid container. This means that its direct children will become grid items, and the container itself will behave like a grid.grid-template-columns
: This defines the number and size of the columns in the grid. In this case,grid-template-columns: 1fr 1fr 1fr;
creates three equal-width columns by dividing the available space into three equal parts (each1fr
representing one fraction of the available space).
And here’s the output:
Note: The image is set to a width of 100% to fill up the fraction of space in the grid column.
Center Images Vertically with Grid
To center an image vertically with a CSS grid, change the code to the following:
<style> .container { width: 100%; display: grid; place-items: center; } .image-wrapper { display: grid; place-items: center; } </style>
Note: The image is set to a width of 50% for this example.
Final Thoughts
We’ve explored Flexbox and CSS Grid as tools for centering images, each with unique strengths tailored to specific use cases. Flexbox shines in scenarios where simplicity meets linear layout needs; it’s the go-to choice for developers looking to center images within containers that may need to be responsive across various screen sizes, especially for single-direction alignments.
On the other hand, CSS Grid steps into the limelight when complexity calls for a more structured approach. It excels in two-dimensional layout arrangements, where control over rows and columns is necessary. This makes it an ideal candidate for more intricate designs, such as photo grids that vary in image size and aspect ratios or when working on a layout that includes text and other elements alongside images.
Transform your digital asset management with Cloudinary’s seamless image and video optimization today! Sign up for free today!