How To Center Image Vertically And Horizontally Using CSS

Home » CSS » How To Center Image Vertically And Horizontally Using CSS

When I started web development, it was difficult to align the image exactly center of the div. At the time, text-align: center did work for me, but I wasn’t so happy.

Since Flexbox was introduced, it has taken almost all efforts away from old techniques. I’ll suggest using only one technique to solve this problem – Flexbox. Using flexbox, we can easily center images vertically and horizontally inside the parent div.

But there are many ways to do the same thing with CSS. I have shortlisted some of the most useful techniques in this article.

1. Flexbox

Using Flexbox properties, we can tell child elements to align themselves properly inside the parent div. This technique works perfectly for space distribution and alignment of children inside.

Nesting Flexbox elements with other elements allows developers to create a complex layout without worrying about its alignment with its siblings.

<style>
.parent {
display: flex;
align-items:center;
justify-content:center;
hieght:100%;
}
</style>
<div class="parent"><img alt="dummy" scr="imgsource" /></div>

How Flexbox Centers The Image

Flexbox uses an algorithm that understands its surroundings. So we have to set flexbox to the parent and apply some properties to make it work.

  • display: flex – Tells the browser to use one-dimensional layout control for the element.
  • align-items: center – aligns all the child elements to the center of the element vertically. The default value is stretch, which will make the image width 100%.
  • justify-content: center – When we have more than one element, justify will tell all elements to stay in the center horizontally.
  • height: 100%: Sets parent height to 100% (this could be any height)
PROS
  • Centers All Child Elements
CONS

2. Display Table

One of the oldest and most compatible techniques is to use tables or display: table and display:table-cell method. Tables have supported vertical centering since the beginning. We can use the vertical-align property to display data in proper alignment. This technique is a hack and doesn’t support text and images being centered together.
By default, text centering is done at the baseline, which may look ugly sometimes.

Our technical experts can help fix any issue you are having with your website, regardless of its complexity.

FIND OUT MORE

&lt;style>
.parent {
display: table;
width:100%;
hieght:100%;
}
.child{
display:table-cell;
text-align:center;
vertical-align:middle;
height:100%;
width:100%;
}
&lt;/style>
&lt;div class="parent">
&lt;div class="child">
&lt;img alt="dummy" scr="imgsource" />&lt;/div>&lt;/div>

How Table Centres The Image

Table hack used two divs to recreate the table and table cell markup. So in the parent div, we use the display table to turn on tabular mode.

  • display: table – Sets div to use properties of the table. This behavior is mandatory in this technique.
  • height: 100% – Sets the height of the table.
  • width: 100% – By Default table uses auto width, so we need to make it full width to image a bit of room for alignment.

Our technical experts can help fix any issue you are having with your website, regardless of its complexity.

FIND OUT MORE

In the table, an additional div is used, which behaves like a table cell. This should be done because vertical alignment is done only on table-cell elements.

  • display: table-cell – Enables Cell Mode
  • text-align: center – Horizontal Centering for the Child Element
  • vertical-align: middle – Vertical Centering for Child Element

The combination of text-align and vertical-align will make the image centered and aligned.

PROS
CONS
  • Text Elements Don't Work With Images

3. Position and Transform

This solution uses the modern CSS3 transform property to move an object around. So we can align the image to the center using any of the position properties and transform the image to half of the negative space of their widths and heights using transform. By doing this, we’ll have a perfectly aligned image with its center origin.

&lt;style>
.parent {
width:100%;
hieght:100%;
position:relative;
}
.parent img{
position:relative;
left:30%;
top:30%;
transform:translate(-30%, -30%);
}
&lt;/style>
&lt;div class="parent">&lt;img alt="dummy" scr="imgsource" />&lt;/div>

How Position And Transform Centres The Image

It’s no magic trick here. But it works great when used with position: relative; it works with position absolute, but it can run into an overflow problem if the image is larger than the parent.

  • position: relative – This is required to move objects in DOM space using left, top, right, and bottom options. This option works with position absolute as well.
  • left: 50% – Moves the Image to the center of the page horizontally. But the Image center is at its left-most point, not at the center.
  • top: 50% – Moves the Image to the center of the page vertically. But the Image center is at the top at this point. It should be at half of the image width.
  • transform: translate(-50%, -50%) – This moves the object from its original position to the negative half distance in both horizontal and vertical axes.
PROS
CONS

4. Position and Margin

The way to use a lazy version of the transform and position method is to replace the transform with obvious values of margins. This is not the most compatible version, but it works for a smaller part of the UI where image dimensions are fixed and we don’t have to worry about the aspect ratio changing often.

<style>
.parent {
width:100%;
hieght:100%;
position:relative;
}
.parent img{
position:relative;
left:50%;
top:50%;
margin:-50px 0 0 -50px;
}
</style>
<div class="parent"><img alt="dummy" scr="imgsource" /></div>

How Position and Margin Centres The Image

This technique is similar to using the transform property. This one just uses margins to make the center transition. You have to know the image width and height to make it work because margins and padding don’t behave like they should when used in percentages. Using padding or margin in percentages is the last thing you ever want to do for this task.

  • position: relative – This is required to move objects in DOM space using left, top, right, and bottom options. This option works with position absolute as well.
  • left: 50% – Moves the Image to the center of the page horizontally. But the Image center is at its left-most point, not at the center.
  • top: 50% – Moves the Image to the center of the page vertically. But the Image center is at the top at this point. It should be at half of the image width.
  • margin:-50px 0 0 -50px – This moves the object from its original position to the negative half distance in both horizontal and vertical axes.
PROS
CONS

5. Object-fit (Hack)

We can use the simple object property of an image to fake the center-aligned look of the image inside the div. This will be considered a hack because the image will take the entire area of the parent, so we can’t have a text element next to it.

<style>
.parent {
width:100%;
hieght:100%;
position:relative;
}
.parent img{
position:absolute;
left:0%;
top:0%;
width:100%;
height:100%;
object-fit:none;
object-position:center;
}
</style>

How Object-fit and Object-position Centres The Image

What this trick does is stretch the image element to the size of its parent. This gives a stretched version of the image. The image is properly placed in the center using object properties.

  • position: absolute – This enables the sizing and moving of an image in the parent div
  • left: 0% – aligns left edge to left of parent
  • top: 0% – aligns the top edge to the top of the parent
  • width: 100% –  makes the width 100%
  • height: 100% – makes height 100%
  • object-fit: none – this will keep the original size of the image, the image’s width and height will be irrelevant when we use the object-fit property.
  • object-position: center – This moves the image object to the center part of the image.
PROS
CONS

6. Background-image (Hack but Worth Mention)

It’s not an actual solution to the problem, but this method is highly used in industry because it’s nonblocking. An image is part of HTML and DOM, so when the page loads, it starts loading.

But if we use an image inside CSS, it makes a difference from a performance standpoint. There are Three Methods to add CSS to HTML. With simple CSS rules, we can make it appear in the center.

&lt;style>
.parent {
width:100%;
hieght:100%;
background-repeat: no-repeat;
background-position:center center;
background-size: 100px 100px;
}
&lt;/style>
&lt;div class="parent">&lt;/div>

How Background-Position Centres The Image

We have to use CSS to load the image in the background, and we can align the background in the center using background properties.

  • width: 100% – Stretches Element to 100% width of its related parent.
  • height: 100%  – stretches element to 100% height of its related parent.
  • background-repeat: no-repeat – Stops repeating pattern and gives a single object.
  • background-position: center center – makes the background center
  • background-size: 100px 100px – This can be the size of the image

Our technical experts can help fix any issue you are having with your website, regardless of its complexity.

FIND OUT MORE

Final Words

Though there are many solutions to the same problem, each solution will work in different types of situations, sizes, and possibilities.  But personally, I suggest using the Flexbox method. It’s just working awesome.

Continue Reading

rhodium

Rhodium Developers

Framework: WordPress – Elementor
Requirement: New custom-made website with SEO optimization
shangri_la
development

Problem

It’s a start-up company and it did not have enough stuff to showcase its work. It faced the challenge of establishing a strong online presence to attract potential clients. They wanted a visually appealing website that would convey their professionalism and expertise.

Our Plan

Execution

1A premium website template was designed in Figma. Blueprints of the home page and other internal pages were created. The color palette has been chosen wisely to exude elegance without compromising usability – sleek beige typography against crisp black backgrounds creates an impactful visual contrast that enhances readability and attention. 

2By using strong visuals such as high-quality images and graphics showcasing their past projects, we aimed to convey their expertise and build trust with potential clients. The overall tone we maintained throughout the design process was professional yet approachable, reflecting the client’s brand image as a reliable and innovative construction company.

3 By incorporating intuitive navigation features and user-friendly interfaces, we ensured seamless browsing experiences for potential clients. By focusing on creating internal pages that offered valuable content and intuitive navigation, we were able to provide users with an immersive and informative experience. With intuitive menu options, easy-to-use contact forms, and visually appealing project showcases, visitors are certain to find exactly what they need with minimal effort.

4 One of the primary goals for this project was to showcase the exceptional quality of their work through an impressive gallery section. By leveraging the power of visually appealing images and intuitive navigation, we successfully transformed their website into a virtual gallery that entices visitors to explore more.

5 A major challenge encountered during the project was effectively showcasing Rodium’s unique approach to building construction. By incorporating captivating visuals and interactive elements, such as 2D models and virtual tours, the website successfully demonstrates the intricate processes involved in constructing high-quality buildings. Additionally, clear and concise descriptions were implemented to explain each step of the construction journey, making it easily understandable for potential clients who may not be familiar with technical jargon.

Final Testing

During the testing phase, every aspect of the website will be put under a microscope to ensure its seamless functionality and performance. From checking cross-browser compatibility to ensuring smooth navigation on different devices and screen sizes, no stone will be left unturned. The comprehensive testing process aims not only to identify any potential glitches or bugs but also to guarantee that the user experience is intuitive and flawless.

By utilizing the latest techniques in search engine optimization algorithms, this website is now primed to attract organic traffic and boost its online presence.