Image Effects How to Create Simple Yet Effective PHP Overlay Understanding Real-Time Image Recognition How to add a shadow effect to an image with CSS How to crop an image in Flutter with Cloudinary How To Rotate an Image with Java Image Processing with Python Rotating an image with CSS Enhancing User Experience with a Responsive Image Slider Building a Python Image Recognition System Building an Interactive JavaScript Image Manipulation Tool Image Align Centering with HTML and CSS Efficient Image Cropping Techniques with Angular and Cloudinary Ultimate Guide to Photo Gallery on Android A Comprehensive Guide to Adding Text to Images on Android Mastering Background Changes in React Applications Comprehensive Guide on Changing Background on Android Devices Mastering Image Rotation in Java A Guide to Adding Text to Images with Python A Guide to Converting Images to Grayscale with Python Introduction Creating an Image Overlay with JavaScript Rotating an Image in Python Creating a Dynamic Photo Gallery with jQuery Creating An Interactive Photo Gallery Using JavaScript Mastering Overlay in Android Mastering Angular Overlay: A Comprehensive Guide Comprehensive Guide to Overlay in Flutter Mastering Overlay React for Responsive Design Solutions Create a Blurred Image with PHP: A Comprehensive Guide Guide to Using Blur Image in Flutter Mastering Blur Image in React Native Mastering Image Blurring in Python Mastering the Art of Image Blurring Mastering the Art of Image Blurring in Java The Ultimate Guide to Blurring Images on Android Understanding and Implementing Blur Image in JQuery An Extensive Walkthrough of Blurring Images with JavaScript How to Use HTML, CSS, and JavaScript to Make an Image Slider HTML Image Tag How to Crop GIFs? How to Align Images with CSS Ken Burns Effect – Complete Guide and How to Apply It Cartoonify – Complete Guide on Cartoonify Image Effect Mastering Web Aesthetics: A Comprehensive Guide to Gradient Fades Sepia Effect: The Ultimate Guide to the Sepia Photo Effect What is Vignette? Guide to Vignette Image Editing Pixelate – The Ultimate Guide to the Pixelation Effect How to Outline an Image: Enhancing Visual Appeal and Depth Make Your Photos Pop with Image Effects Upscale Image – Developers guide to AI-driven image upscaling Image Manipulation: History, Concepts and a Complete Guide A Full Guide to Object-aware Cropping Simplify Your Life with Automatic Image Tagging How To Resize Images In WordPress How To Create a Progress Bar For Asset Uploads Animated GIFs – What They Are And How To Create Them How To Automatically Improve Image Resolution AI Drop Shadow Get Image Dimensions From URLs Automatically Add Sepia Effect To Images Automatically Make an Image a Cartoon Automatically Add Blur Faces Effect To Images Automatically Add Background Removal Effect to an Image How to Resize an Image with React How to Easily Resize an Image with React Native

Image Align Centering with HTML and CSS

image align center html css

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

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:

image align center html css

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:

image align center html css

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:

image align center html css

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.

image align center html css

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:

image align center html css

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:

image align center html css

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 (each 1fr representing one fraction of the available space).

And here’s the output:

image align center html css

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>

image align center html css

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!

Last updated: May 26, 2024