439

I have a div 200 x 200 px. I want to place a 50 x 50 px image right in the middle of the div.

How can it be done?

I am able to get it centered horizontally by using text-align: center for the div. But vertical alignment is the issue..

2

35 Answers 35

451

Working in old browsers (IE >= 8)

Absolute position in combination with automatic margin permits to center an element horizontally and vertically. The element position could be based on a parent element position using relative positioning. View Result

img {
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}
15
  • 60
    just make the div relative #someDiv { position: relative } Dec 5, 2012 at 15:12
  • 3
    This worked great for me, and helps when you do not have the exact size of either the container DIV or the image. Thanks!
    – Charlie74
    Oct 12, 2013 at 13:45
  • 3
    You can also center exclusively horizontal by omitting the top and bottom, and center exclusively vertical by omitting the right and left. Jul 31, 2014 at 15:16
  • 1
    @YoLudke, yes, you can. just include max-width:100%; height:auto;. you can also make it aligned to any of the sides by omitting that side. pretty cool.
    – robotik
    May 24, 2015 at 7:12
  • 1
    This solution can add "max-height: 100%; max-width: 100%;" to make image perfectly fit div.
    – Wei Kleeff
    Oct 30, 2017 at 18:09
337

Personally, I'd place it as the background image within the div, the CSS for that being:

#demo {
    background: url(bg_apple_little.gif) no-repeat center center;
    height: 200px;
    width: 200px;
}

(Assumes a div with id="demo" as you are already specifying height and width adding a background shouldn't be an issue)

Let the browser take the strain.

7
  • 10
    This is usually the best answer, unless the size of the image can vary from smaller to bigger than the container's size. In the 'smaller' case, it will be fine, but in the 'bigger' case, your image will be clipped.
    – leandre_b
    Jul 11, 2011 at 15:52
  • 96
    Not as SEO/reader friendly if you want to add an ALT attribute.
    – e11s
    Aug 27, 2011 at 2:35
  • 2
    What about if we are using a sprite? I am trying to center the background image, but I'm using a CSS sprite. Any ideas?
    – Nathan
    Nov 23, 2011 at 3:43
  • @Nathan this is not an easy task. You can do it though if you know the exact dimensions of the div and leave enough transparent space around the image on the sprite so that the other images on the sprite are not displayed. Dec 5, 2012 at 15:16
  • 1
    My images are always have a different size, How to applied this when image have different different size ? Oct 10, 2014 at 11:17
110

another way is to create a table with valign, of course. This would work regardless of you knowing the div's height or not.

<div>
   <table width="100%" height="100%" align="center" valign="center">
   <tr><td>
      <img src="foo.jpg" alt="foo" />
   </td></tr>
   </table>
</div>

but you should always stick to just css whenever possible.

7
  • 45
    I knew that this would get me down-voted. I thought about listing this just for the sake of completeness, but, oh well.
    – andyk
    Dec 23, 2008 at 14:09
  • 54
    Don't you know that using tables causes blindness?
    – Pekka
    Dec 28, 2009 at 18:23
  • 25
    CSS when possible, but this is definitely a useful fallback. Don't forget why we stopped using tables in the first place. Use whatever is the most flexible solution. Sometimes this is it. Mar 24, 2010 at 14:49
  • 22
    Note: This may have been "acceptable" in 2008, but in 2012, this is never, ever acceptable.
    – animuson
    Jan 19, 2012 at 19:58
  • 36
    Objection, animuson: All the other solutions here assume that you know the image size as they appear in the browser, which is not the case if you design a responsive layout where your image is "height:100%" and it's container is "width:25%", leaving you with an x or y margin of unknown size. Jul 18, 2012 at 3:09
81

I would set your larger div with position:relative; then for your image do this:

img.classname{
   position:absolute;
   top:50%;
   left:50%;
   margin-top:-25px;
   margin-left:-25px;
}

This only works because you know the dimensions of both the image and the containing div. This will also let you have other items within the containing div... where solutions like using line-height will not.

EDIT: Note... your margins are negative half of the size of the image.

3
  • 5
    I used this, but removed margin bits and adding -webkit-transform: translateY(-50%); -moz-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%);. Gives more generic solution that does need element size.
    – Jon
    Sep 13, 2013 at 21:24
  • Tried this it moves the image up if smaller than the div.
    – some_guy
    Nov 26, 2022 at 13:58
65

This works correctly:

display: block;
margin-left: auto;
margin-right: auto 

else try this if the above only gives you horizontal centering:

.outerContainer {
   position: relative;
}

.innerContainer {
   width: 50px; //your image/element width here
   height: 50px; //your image/element height here
   overflow: auto;
   margin: auto;
   position: absolute;
   top: 0; left: 0; bottom: 0; right: 0;
}
1
  • 3
    Or use display: block; margin: auto; for the simplest.
    – ch271828n
    May 1, 2016 at 4:07
57

Use Flexbox:

.outerDiv {
  display: flex;
  flex-direction: column;
  justify-content: center;  /* Centering y-axis */
  align-items :center; /* Centering x-axis */
}
1
  • Nice! This actually worked and helps if you can't place the image as background, as suggested in the previous answer. Dec 5, 2017 at 12:35
41

here's another method to center everything within anything.

Working Fiddle

HTML: (simple as ever)

<div class="Container">
    <div class="Content"> /*this can be an img, span, or everything else*/
        I'm the Content
    </div>
</div>

CSS:

.Container
{
    text-align: center;
}

    .Container:before
    {
        content: '';
        height: 100%;
        display: inline-block;
        vertical-align: middle;
    }

.Content
{
    display: inline-block;
    vertical-align: middle;
}

Benefits

The Container and Content height are unknown.

Centering without specific negative margin, without setting the line-height (so it works well with multiple line of text) and without a script, also Works great with CSS transitions.

2
  • +1. Great solution and very good SO answer. I'm wondering what's causing the browser to do the (expected) behaviour only by adding the before pseudoclass with content: "" (Because many of us might have tried display: inline-block and vertical-align: middle without success). Mar 29, 2014 at 19:17
  • 1
    it's actually very simple. you create an empty element inside the container that spans 100% height, and then you align your element with the center of this empty one. causing your element to be in the exact center of the container. Mar 29, 2014 at 20:31
31

This is coming a bit late, but here's a solution I use to vertical align elements within a parent div.

This is useful for when you know the size of the container div, but not that of the contained image. (this is frequently the case when working with lightboxes or image carousels).

Here's the styling you should try:

 container div
 {
   display:table-cell;
   vertical-align:middle;

   height:200px;
   width:200px;
 }

 img
 {
   /*Apply any styling here*/        
 }
5
  • 1
    +1 for showing me a away to make a CSS div behave like a table cell, now I can avoid further countless hours of frustration getting CSS to do what is simple to do with a traditional HTML table cell
    – Kmeixner
    Mar 17, 2013 at 15:25
  • 3
    add in text-align:center; to container div and it's centered both directions if you're applying a max height/width to an unknown sized image. Jul 2, 2013 at 23:53
  • 2
    best answer in my opinion. and dont forget the text-align: center; Apr 28, 2015 at 6:30
  • Note: By default img elements are inline and will need to be set to 'block' to be in vertical middle. img { display: block; } Jan 8, 2016 at 12:21
  • This answer seems better than the oter ones who that got more votes. It works regardless of third-party frameworks or combination of styles in multiple elements. Mar 22, 2018 at 16:23
21

I've found that Valamas' and Lepu's answers above are the most straightforward answers that deal with images of unknown size, or of known size that you'd rather not hard-code into your CSS. I just have a few small tweaks: remove irrelevant styles, size it to 200px to match the question, and add max-height/max-width to handle images that may be too large.

div.image-thumbnail
{
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
}
div.image-thumbnail img
{
    vertical-align: middle;
    max-height: 200px;
    max-width: 200px;
}
0
13

in the div

style="text-align:center; line-height:200px"
2
  • But this doesnt seem to work if the div just contains the image (FF3). code: <div style="border: 1px solid #ccc; margin: 20px; height: 200px; width: 200px;"> <img src="sun.gif" /> </div> Am I missing anything?
    – Shameem
    Dec 23, 2008 at 6:21
  • This does not really do what the question asked and is only supposed to work for text (and only centers the aimage/text vertically) The accepted answer is the most apropriate solution afaik. Sep 28, 2009 at 12:29
13

We can easily achieve this using flex. no need for background-image.

<!DOCTYPE html>
<html>
<head>
   <style>
      #image-wrapper{
         width:500px;
         height:500px;
         border:1px solid #333;
         display:flex;
         justify-content:center;
         align-items:center;
      }
   </style>
</head>
<body>

<div id="image-wrapper">
<img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png">
</div>

</body>
</html>

12

Vertical-align is one of the most misused css styles. It doesn't work how you might expect on elements that are not td's or css "display: table-cell".

This is a very good post on the matter. http://phrogz.net/CSS/vertical-align/index.html

The most common methods to acheive what you're looking for are:

  • padding top/bottom
  • position absolute
  • line-height
12

In CSS do it as:

img
{

  display:table-cell;
  vertical-align:middle;
  margin:auto;
}
3
  • 2
    Thats only make it horizontal center. If you provide auto for top and bottom margin, browsers take it as zero by default. May 30, 2012 at 7:52
  • 5
    Doesn't work - jsfiddle.net/dandv/umBRF, though the reason is not the margin-top/bottom as knoxxs suggests. For the image to display as a table-cell, it needs a parent element to have display: table-cell; vertical-align: middle; - jsfiddle.net/dandv/umBRF/1 Sep 4, 2012 at 4:54
  • 1
    Close, but the display and vertical-align properties need to be applied to the container, not the thing being centered. (See Kshitij Chopra's answer)
    – Faust
    Jul 1, 2013 at 8:44
11

@sleepy You can easily do this using the following attributes:

#content {
  display: flex;
  align-items: center;
  width: 200px;
  height: 200px;
  border: 1px solid red;
}

#myImage {
  display: block;
  width: 50px;
  height: 50px;  
  margin: auto;
  border: 1px solid yellow;
}
<div id="content">
  <img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png">
</div>

References: W3

0
9

I have a gallery of images for which I don't know the exact heights or widths of images beforhand, I just know that they are smaller than the div in which they are going to be contained.

By doing a combination of line-height settings on the container and using vertical-align:middle on the image element, I finally got it to work on FF 3.5, Safari 4.0 and IE7.0 using the following HTML markup and the following CSS.

The HTML Markup

<div id="gallery">
    <div class="painting">
        <a href="Painting/Details/2">
            <img src="/Content/Images/Paintings/Thumbnail/painting_00002.jpg" />
        </a>
    </div>
    <div class="painting">
        ...
    </div>
    ...
 </div>

The CSS

div.painting
{
    float:left;

    height:138px; /* fixed dimensions */
    width: 138px;

    border: solid 1px white;
    background-color:#F5F5F5;


    line-height:138px;    
    text-align:center;

}

    div.painting a img
    {
        border:none;
        vertical-align:middle;

    }
8

Typically, I'll set the line-height to be 200px. Usually does the trick.

6

This works for me :

<body>
  <table id="table-foo">
    <tr><td>
        <img src="foo.png" /> 
    </td></tr>
  </table>
</body>
<style type="text/css">
  html, body {
    height: 100%;
  }
  #table-foo {
    width: 100%;
    height: 100%;
    text-align: center;
    vertical-align: middle;
  }
  #table-foo img {
    display: block;
    margin: 0 auto;
  }
</style>
6

Another way (not mentioned here yet) is with Flexbox.

Just set the following rules on the container div:

display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */

FIDDLE

div {
  width: 200px;
  height: 200px;
  border: 1px solid green;
  display: flex;
  justify-content: center;
  /* align horizontal */
  align-items: center;
  /* align vertical */
}
<div>
  <img src="http://lorempixel.com/50/50/food" alt="" />
</div>

A good place to start with Flexbox to see some of it's features and get syntax for maximum browser support is flexyboxes

Also, browser support nowadays is quite good: caniuse

For cross-browser compatibility for display: flex and align-items, you can use the following:

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
0
6

This is an old solution but browser market shares have advanced enough that you may be able to get by without the IE hack part of it if you are not concerned about degrading for IE7. This works when you know the dimensions of the outer container but may or may not know the dimensions of the inner image.

.parent {
    display: table;
    height: 200px; /* can be percentages, too, like 100% */
    width: 200px; /* can be percentages, too, like 100% */
}

.child {
    display: table-cell;
    vertical-align: middle;
    margin: 0 auto;
}
 <div class="parent">
     <div class="child">
         <img src="foo.png" alt="bar" />
     </div>
 </div>
5

easy

img {
    transform: translate(50%,50%);
}
0
4

You can set position of image is align center horizontal by this

#imageId {
   display: block;
   margin-left: auto;
   margin-right:auto;
}
1
  • User needs alignment for both positions, this only solves half his question and, depending on the context of your code, not even that. Feb 1, 2017 at 23:55
4

I've been trying to get an image to be centered vertically and horizontally within a circle shape using hmtl and css.

After combining several points from this thread, here's what I came up with: jsFiddle

Here's another example of this within a three column layout: jsFiddle

CSS:

#circle {
width: 100px;
height: 100px;
background: #A7A9AB;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
margin: 0 auto;
position: relative;
}

.images {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}

HTML:

<div id="circle">
<img class="images" src="https://png.icons8.com/facebook-like-filled/ios7/50" />
</div>
3

You can center an image horizontally and vertically with the code below (works in IE/FF). It will put the top edge of the image at exactly 50% of the browser height, and the margin-top(pulling half the height of the image up) will center it perfectly.

<style type="text/css">
    #middle {position: absolute; top: 50%;} /* for explorer only*/
    #middle[id] {vertical-align: middle; width: 100%;}
         #inner {position: relative; top: -50%} /* for explorer only */
</style>


<body style="background-color:#eeeeee">
    <div id="middle">
        <div id="inner" align="center" style="margin-top:...px"> /* the number will be half the height of your image, so for example if the height is 500px then you will put 250px for the margin-top */
            <img src="..." height="..." width="..." />
        </div>
    </div>
</body>
3

I love jumping on old bandwagons!

Here's a 2015 update to this answer. I started using CSS3 transform to do my dirty work for positioning. This allows you to not have to make any extra HTML, you don't have to do math (finding half-widths of things) you can use it on any element!

Here's an example (with fiddle at the end). Your HTML:

<div class="bigDiv">
    <div class="smallDiv">
    </div>
</div>

With accompanying CSS:

.bigDiv {
    width:200px;
    height:200px;
    background-color:#efefef;
    position:relative;
}
.smallDiv {
    width:50px;
    height:50px;
    background-color:#cc0000;
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
}

What I do a lot these days is I will give a class to things I want centered and just re-use that class every time. For example:

<div class="bigDiv">
    <div class="smallDiv centerThis">
    </div>
</div>

css

.bigDiv {
    width:200px;
    height:200px;
    background-color:#efefef;
    position:relative;
}
.smallDiv {
    width:50px;
    height:50px;
    background-color:#cc0000;
}
.centerThis {
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
}

This way, I will always be able to center something in it's container. You just have to make sure that the thing you want centered is in a container that has a position defined.

Here's a fiddle

BTW: This works for centering BIGGER divs inside SMALLER divs as well.

0
2

div {
  position: absolute;
  
  border: 3px solid green;
  width: 200px;
  height: 200px;
}

img { 
  position: relative;
  
  border: 3px solid red;
  width: 50px;
  height: 50px;
}

.center {    
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%); /* IE 9 */
  -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */
}
<div class="center">
  <img class="center" src="http://placeholders.org/250/000/fff" />
</div>

Related: Center a image

1

thanks to everyone else for the clues.

I used this method

div.image-thumbnail
{
    width: 85px;
    height: 85px;
    line-height: 85px;
    display: inline-block;
    text-align: center;
}
div.image-thumbnail img
{
    vertical-align: middle;
}
1

Use positioning. The following worked for me:

div{
    display:block;
    overflow:hidden;
    width: 200px; 
    height: 200px;  
    position: relative;
}
div img{
    width: 50px; 
    height: 50px;   
    top: 50%;
    left: 50%;
    bottom: 50%;
    right: 50%;
    position: absolute;
}
1
.container {
height: 200px;
width: 200px;
float:left;
position:relative;
}
.children-with-img {
position: absolute;
width:50px;
height:50px;
left:50%;
top:50%;
transform:translate(-50%);
}
1
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Jan 23, 2017 at 12:41
0

If you know the size of the parent div and the image, you can just use absolute positioning.

5
  • This doesn't answer the question, it's nothing more than a hint.
    – cimmanon
    Feb 17, 2016 at 12:03
  • Potato, potato. I think it is an answer, although maybe not a great one.
    – recursive
    Feb 17, 2016 at 17:26
  • How do you figure this answers the question? At best, the OP knows that they'll have to look at another answer to figure out what this means (like this answer that was posted almost a full hour before yours. At worst, it's useless noise.
    – cimmanon
    Feb 17, 2016 at 17:47
  • I think you're underestimating the best case. In the best case, the OP knows what absolute positioning is, and can implement it directly. I do agree that it seems rather pointless for this answer to exist, given that it doesn't seem to add much to previous ones. I don't remember what I was thinking. It's been a while!
    – recursive
    Feb 17, 2016 at 17:57
  • 1
    Answers that attempt to answer the question are still answers. If you don't like an answer or think that an answer is wrong, down-vote the answer. Maybe you'll be able to shame the answer's answerer into deleting their own answer. When to flag an answer as “it is not an answer”?
    – twernt
    Feb 17, 2016 at 19:00
0

This worked for me. Add this to image css:

img
{
   display: block;
   margin: auto;
}
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.