Centering an Image in CSS: A Detailed Guide

Alex Anie

Posted On: February 26, 2024

view count83771 Views

Read time23 Min Read

Images are widely used on websites and play an important role in helping users understand and find different types of information on the web. Therefore, proper alignment of images on the websites is crucial to avoid issues like overflow or unnecessary scrolling caused by large images.

When it comes to working with images, primarily centering an image in CSS can be a challenging task, especially for beginners. This is due to the fact that the < img > tag works as an internal element; it behaves differently compared to block elements, which complicates the process of centering an image in CSS.

In this guide, we will explore different methods of centering an image in CSS.

Why Centering an Image in CSS?

Centering an image in CSS is very crucial to the overall layout of the webpage. Depending on the approach used, images can be embedded on the web using an HTML < img > tag or CSS background-image property.

When an image is embedded on the web due to its large size or repeats within the parent element. To enable the image to fit well on its defined element, it has to be resized to prevent it from overflowing and to take the size of its parent element.

With this, images can be properly centered and positioned. For example, the illustration below shows how this can be done using three card elements on the web page with the image as a header attached to each element.

header attached to each element

Another example can be seen from Etsy, where images are categorized into different sections, each with a fixed width and height of its parent element. This makes it easy to center and position the images across the web page.

Etsy

The above Etsy website shows good consistency across all elements, contributing to more responsive content, cohesive layout, readability of text, and no overflow of text and images.

From the Amazon website below, you can see good use of CSS grid in centering images around the webpage. This is very useful as it improves the website layout system and aligns the image element in a cohesive and responsive manner.

Amazon

When images are well-centered, it leads to a structured layout of responsive elements across different viewport sizes. This improves UI aesthetics, cohesive layout, and seamless user experience.

Info Note

Test across 3000+ browsers and devices instantly. Try LambdaTest Today!

Techniques for Centering Images Within the Page

Centering images on the web varies depending on the block level of the containing element (parent) of the image you are trying to center.

For example, a website like Walmart uses a CSS flexbox and grid to center multiple images on its platform. This makes it more responsive and allows each image to maintain its aspect ratio within its element.

Walmart

However, other methods such as CSS position, transform, and margin: auto can also center images across the web page. Depending on how the image is included on the web, such as the < img / > tag or the background-image property, we could use the grid, flexbox, CSS position, margin: auto, or the translate property to center images around the web page.

In the next section of this blog, we will learn different techniques for centering an image in CSS.

Centering an Image in CSS Flexbox

CSS flexbox is a one-dimensional layout system for positioning elements in rows and columns. With flexbox, elements (flex-items) can be positioned within the flex container. The flex container, in this case, refers to the containing element the flex-items are nested in. To position images to the center, justify-content and align-items are used on the container.

justify-content and align-items

It is a common practice that images are set to inherit the size of the parent element. This makes it easy to center it across other elements within the webpage.

With justify-content, flex-items can be centered horizontally within the parent element, and with align-items, flex-items can be centered vertically.

justify-content and align-items

Here, we combinedjustify-content and align-items to center the flex-items on the horizontal and vertical axis.

HTML:

Here, within the HTML tag, the following tags performed the functions below

  • < main >: With a class of container, this tag serves as the parent tag of the card element on the webpage.
  • < section >: A nested tag of the < main > tag that serves as a wrapper for both the image, buttons, and content of the card element.
  • < img >: Here, we parse in a user profile as the hero image of the card element.
  • < button >: We implement two buttons to serve as a call to action on the card element.
  • < p >: The paragraph tag contains the content on the page.

These HTML tags are used to structure the page content, while the CSS below is used to style it.

CSS:

To center the card element from the horizontal and vertical axes, we do the following.

  • The body element is set at a width and height of 100vw and 100vh, respectively, providing enough space for the element to be positioned around the container.
  • The < main > element with the class container is set to display flex to help center the entire content to the center of the page.
  • The < section > tag is set to relative and a width of 22em to serve as the width of the children element.
  • The < img > tag takes a width of 100%> to inherit the parent default width size and height of auto.
  • The < button > tags are styled as CTA buttons with a transparent background and a background of gray on hover.

Each element within the parent card element is styled to fit into the parent container for easy alignment around the webpage.

See the Pen
Centering Image in CSS: Flexbox — flex-item
by Ocxigin (@ocxigin)
on CodePen.

flex-self

From the previous example, we learned how justify-content and align-items are used to center flex-items within their container. When in use, justify-content and align-items affect all flex-items within the container.

However, where a particular flex item is required to be repositioned aside from other flex items within the same container, flex-self is used. The flex-self helps reposition each flex item within its flex container.

flex-self

Here each flex item is repositioned using the flex-self property.

HTML:

CSS:

From the code example above, we have a parent container (< section > tag) with three child elements (< img > tags). The parent element is set to a display of flex, and each child element is set to start, center, and end, respectively, within the flex-container.

The black solid border around the parent element (< section > tag) serves as a visual reference to the amount of space within the parent element and how each flex item (images) is positioned with the flex container.

See the Pen
Centering Image in CSS: Flexbox — flex-self
by Ocxigin (@ocxigin)
on CodePen.

Centering an Image in CSS Grid

The CSS grid system is a two-dimensional layout method for positioning elements around the web page. The CSS grid is the most powerful CSS layout system that enables web elements to be positioned between rows and columns at the same instance.

place-content

The CSS grid system comes with lots of properties, such as ways for positioning grid items within the grid container. One of which is the place-content property. The CSS grid place-content property is a short-hand property for align-content and justify-content properties.

This is very useful when you need to set grid items within the grid container. The place-content property aligns the grid items with the grid cells in a horizontal and vertical direction within the grid container.

grid items

Here, the grid place-content property is used to position the grid items along the horizontal and vertical axes.

HTML:

CSS:

The code above can be broken into sections as follows.

  • The section tag is the parent tag, nested inside this tag are four < img > tags. The section tag is set to display a grid and a place-content property to center the content around the webpage.
  • The image tags are set to a width and height of 20em and position relative to the section tag.

The section tags contain four direct children elements; using the place-content helps align all items around the container.

See the Pen
Centering Image in CSS: Gird – place-items
by Ocxigin (@ocxigin)
on CodePen.

place-items

The CSS grid place-items property is used to align the grid items in a horizontal and vertical direction within the individual grid cells in a grid container. The place-items property is a shorthand property for justify-items (horizontal alignment) and align-items (vertical alignment) used to control the alignment of grid items within their grid cells.

horizontal alignment

With the place-item property, each grid item is aligned within its grid cells. The grid cells are single-units of boxes arranged in a row and column layout within the grid container. When a grid is defined as a container, each grid item is assigned a cell. However, the place-items property lets us align the grid items within their cells.

To see a visual reference on place-items alignment on the cell, We can turn on the Chrome DevTools and click on the small grid icon on the element tab as indicated below.

place-items

The grid cells are the square boxes around the card elements; from the image above, you can see how each card element is aligned to the center of their grid cells.

HTML:

CSS:

From the code sample above, we have four < aside > elements with classes of child1 to child4 and children and an < section > element with a class of parent.

  • parent: The parent class is set to display a grid to make the element a grid container, then a grid-template-columns is set to repeat(2, 400px) and a grid-template-rows: 400px; this will provide more space for cells within the grid container and split them into a two-column grid. The gap of 10px creates a space between the cells, and the place-items property sets the grid-items to center horizontally and vertically within the grid cell.
  • children: The children class is the grid-items. It takes a width of 200px each within the grid container.

When centering an image, the place-items align the image within the cells of the grid container, which is very useful for websites with multiple images.

See the Pen
place-items
by Ocxigin (@ocxigin)
on CodePen.

justify-self

The justify-self property functions the same way as the flex-self property but for the grid system.
With the justify-self property, individual grid items can be re-aligned within the grid container.

grid container

From the example above, the first grid item is set to align to the end of its appropriate axis, while the third grid item is set to start from the appropriate axis.

HTML:

CSS:

Here, < section > tag serves as the parent tag with six direct < img > elements. The < section > element is set to a display of grid and grid-template-column of 3. With these, each grid item is split into 3 columns around the grid-container. With justify-self, individual items are re-aligned within the grid-container.

For example, the div:nth-child(1) is set to justify-self: end to reposition the image to the end position with the grid container.

See the Pen
Centering Image in CSS: Gird – justify-self
by Ocxigin (@ocxigin)
on CodePen.

margin: auto

The margin property can be set to auto to automatically align an image in a block container to the center, based on the size of the parent.

block container

Specified element will occupy the space set by the width property and minus its width from the parent width.

The element will then be positioned in the middle of the page or containing the element, leaving the same proposition of space left and right of the element.

same proposition

HTML:

CSS:

The margin: auto is mainly used for block elements. As you can see from the code sample above, the < section > tag is set to occupy 50% of the parent container within the webpage. A margin: 0 auto is set to push the child element to the center of the page.

See the Pen
margin auto
by Ocxigin (@ocxigin)
on CodePen.

position

The position property is an effective way to center an image. With the position property, images or elements can be centered or positioned around the document using the position properties such as left, right, top, and bottom.

position: absolute property changes the stacking context of the document. Adding position: relative can help images or elements be centered around the parent element.

parent element

HTML:

CSS:

From the above code, the position property effect can be seen from the position: absolute, top: 50%, and left: 50%. This helps reposition the card element at the center of the page relative to the < main > element.

See the Pen
position in css
by Ocxigin (@ocxigin)
on CodePen.

transform: translate

The translate property sets how elements can be repositioned from their initial layout or document flow. For example, we could reposition images or elements around the document. To do this, we use the transform: translate property.

The transform: translate property has both X (horizontal) and Y (vertical) coordinates for horizontal and vertical positioning.

By default, elements are set to translate: 0px, meaning no translation is set. Using the length CSS units like px, em, rem, and %, images can be repositioned around the webpage.

repositioned around the webpage

HTML:

CSS:

From the code sample above, the section element contains three card elements, and each element is set to a transform: translate of 150% on the horizontal axis and 100% on the vertical axis to realign the element around the webpage.

See the Pen
translate in css
by Ocxigin (@ocxigin)
on CodePen.

Techniques for Centering an Image in CSS Within Container

Depending on how the image is included on the web, such as the < img /> tag or the background-image property we could use object-position or background-position CSS property to center images within its container. The image container refers to the element in which the image is embedded.

In this blog section on centering an image in CSS, we will learn different techniques that can be implemented to center an image within the container of the image using CSS.

background-position

The CSS background-position property is used to position images set by the background-image property within the element container. With the background-position property, we can specify the image’s position within the element container based on the value provided.

These values, however, consist of keywords top, button, left, right, and center—length units like px, em, rem,and %.

length units

Additionally, the background-position property exists on X (horizontal) and Y (vertical) coordinates. With this, images can be positioned on a single coordinate or both (axis).

background position

HTML:

CSS:

JavaScript:

Here, from the code above, we have the following functions

  • The bgImage variable is used to store the background element. With this, an element can manipulate the background position of the image parsed to the element.
  • The allButtons variable is used to store all the button elements.

With the allButtons variable, we added a forEach function to loop through each returned element (node list) and add an eventListener.

Using the if statement to check and change the background position of the element, if the index of the element clicked on is equal to the value parsed in.

object-position

When images are included using the < img /> tag, using the object-position property can be very useful to reposition the image inside the parent box.

The object position property takes keyword values like; top, bottom, left, right, center, and length units such as px, rem, and em to position the image to a specific area within the parent box. It also takes % values to specify the position of the image relative to the parent width and height.

width and height

HTML:

CSS:

JavaScript:

See the Pen
object position
by Ocxigin (@ocxigin)
on CodePen.

Tips for Centering an Image in CSS

CSS properties play a huge role in how images are centered and positioned around the webpage or within the element container. However, other factors such as the image container, image size, scaling, and image data determine how images are positioned on the web page.

In this section, we’ll explain tips for centering an image in CSS within the containing element to create a structured and responsive layout.

Image Container

The image container plays a huge role in how images are centered on the web. The image container is simply the direct parent element that the < img /> tag is nested in. For example, if you create a < div > tag and place an < img /> tag inside the < div > tag, the < div > is the parent element (image container), not the < img /> tag itself.

Image Container

However, if you import the image with the background-image CSS property on a < div > tag. The < div > that received the image as its background image is the image container.

 background-image CSS property

From the image above, we have two image containers, the two image containers are centered around the page using flexbox. However, the second image on the right is centered within its container using the background-position property.

HTML:

CSS:

This CSS code includes styling for a responsive layout with flexbox and card dimensions. Each card is styled as follows.

  • Card one: From the first card element, the width and height are set to 300px, respectively, and inside this element, we nested a < img > tag and set the width to 100% to inherit the default size of the element.
  • Card two: From the second element, the width and height are set to 300px, respectively. With the background-image property, we specify an image and set the size using the background-size property. The image is then centered with the background-position property.

The containing element is essential and plays a huge role in centering elements on the web when proper sizing is implemented.

See the Pen
image container
by Ocxigin (@ocxigin)
on CodePen.

Sizing Images

Images come in large file sizes, making it impossible to center on the web page. Unsized images can lead to unwanted scrollbars and break the page layout. Most images pop out of the element box when it is not size.

The essence of sizing or resizing images in CSS is to ensure consistency across multiple and different elements and for images to take the shape of an element or layout.

CSS itself does not directly handle the content of images, but it does provide properties and rules that allow you to control the size of images within HTML documents.

header attached to each element

With the width, max-width, min-width, height, min-height, and max-height properties, we can resize images with CSS to fit within the image container.

resize images with CSS to fit within the image container

From the browser output above, each image is resized to fit into the container of the image element, making it easy to position around the webpage and within the image container.

HTML:

CSS:

From the code above, the < img > element with a class of head-img is set to 100% width and 200px height. This enables each image to fit into the parent container. However, the second < img > is set to a border-radius of 100px to round the image to a circle.

See the Pen
sized
by Ocxigin (@ocxigin)
on CodePen.

Scaling Images

The best way to scale images in CSS is by sizing, but sometimes this is not enough, especially when the image aspect ratio, resolution, or orientation does not correspond to the width and height of the image-container. The image can easily become distorted or compressed.

This is not good for readability purposes as visitors might find it difficult to read the content on the image.

To fix this, CSS provides properties such as object-fit, margin: auto, aspect-ratio, background-size, flex-grow, and flex-basis.

These properties are very useful for creating and developing responsive layouts. This ensures images are responsive relative to the device or screen resolution that loads the image.

When the aspect ratio of images is maintained across different viewports, it prevents distortion and leads to more fitting looks on the webpage.

Scaling Images

HTML:

CSS:

From the code above, object-fit cover, object-fit contain, and aspect-ratio property is used to set the four < img > elements to scale relative to the parent element, creating a responsive layout across different viewports.

For example, the images below show a good use case using the LT Browser. The scaled images display responsively across different screen sizes for better navigation.

LT Browser is a free, Chromium-based web browser specifically for web developers. It excels at responsive testing and debugging websites and web applications across different screen sizes. This makes it an ideal tool for ensuring your image centering in CSS works flawlessly on all platforms.

Loaded with 53+ pre-installed device viewports, LT Browser includes popular mobiles, tablets, and desktops. It allows you to see how your website reacts across various screen sizes and resolutions. This lets you instantly check if your CSS image centering adapts properly. You can identify issues like images overflowing the content area, cropped unexpectedly, or inconsistent spacing on different devices.

Mobile:

Mobile

Tablet:

Tablet

Laptop:

Laptop

Get to know the different features that LT Browsers offers. Check out the tutorial below:

Catch up on the latest testing tutorials around Selenium automation, Cypress testing, and more. Subscribe to the LambdaTest YouTube Channel for quick updates.

Image Data/Metadata

Image data refers to the data that makes up the content of the actual image, such as pixel information, size, orientation, resolution, RGB color mode, etc. The image data determines how the image in the browser is rendered and how it will be affected or positioned with CSS styling.

However, in the content of the image metadata, which differs from the image data, the image metadata deals with the extra text information that describes what the image is about. For example the name of the image, the date and time it was taken, and the name of the software or camera used to create the image.

The image metadata is very useful and can improve search engine optimization, making images easy to discover and providing accurate details to protect an image against copyright infringement.

Browser Compatibility

Centering images on the web heavily relies on CSS. It provides properties for styling and controlling the appearance and positioning of images on the web. However, due to browser incompatibility with some CSS properties, certain browsers might not load some properties, leading to unexpected image breaking.

To check and fix this, we can use AI-powered test orchestration and execution platforms like LambdaTest to test how the images on our websites are centered across multiple browsers such as Chrome, Firefox, Opera, Safari, Brave, etc. This platform offers an online browser farm of real desktop and mobile environments. Cross browser testing gives visual feedback on how web elements render on the web pages. This makes it easy to visually test and debug web elements on the web page.

Also, CSS properties browser support can be checked via CanIUse to understand when and how to implement such properties for better optimization.

Browser Compatibility

Source

For example, the background-filter used in the last example is partially supported in Safari and requires the use of -webkit- prefix for rendering the background-filter property.

 background-filter property

Ensuring CSS properties used in centering images are well-supported or prefixed can help prevent unwanted or poor image rendering.

Conclusion

In this guide, we explained how to center images in CSS and its significance.

We also discussed two techniques of centering an image in CSS: within a page and in a container.

In the technique for centering an image in CSS within the web page, we explained using properties like flexbox, grid, margin: auto, position properties, and transform: translate property and how they can be implemented in centering images around the web page.

And in the technique for centering images in CSS within its container, we highlight the use of background-position and object-position properties as a method for positioning images within the element container.

We also touched upon other important factors that affect centering an image in CSS, such as the image container, sizing, scaling, and browser compatibility.

Frequently Asked Questions (FAQs)

How do I center an image in CSS?

For horizontal centering, wrap your image in a div and set text-align: center for the div. Alternatively, use margin: 0 auto on the image itself, but remember to set a width if needed. The flexbox approach involves setting the container’s display to flex and justify-content to center.

How to position an image in CSS?

The test automation pyramid is a graphical strategy model for automating software testing. The model divides testing types into three layers based on the return on investment (ROI) provided by automating that specific type.

How do I center an absolute image in CSS?

To center an absolute image horizontally, set position: absolute, left: 50%, and transform: translateX(-50%). For vertical centering, add top: 50% and transform: translateY(-50%). Remember, absolute positioning removes the image from the normal document flow, so it won’t interact with other elements as expected.

Author Profile Author Profile Author Profile

Author’s Profile

Alex Anie

A Front End Technical Writer. I write blogs on Front End Technologies, such as HTML, CSS, JavaScript. When I am not coding, I enjoy watching tutorials and listening to twitter spaces. I live in Lagos, Nigeria

Blogs: 15



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free