0

How to an image in the center of a DIV (both vertically and horizontally) ?

James P.
  • 19,313
  • 27
  • 97
  • 155
Bader
  • 3,656
  • 9
  • 38
  • 55
  • 2
    Possible duplicate of http://stackoverflow.com/questions/388180/how-to-make-an-image-center-vertically-horizontally-inside-a-bigger-div – j08691 Jan 26 '12 at 17:00
  • 3
    can you be anymore vague? ;) you can set it as a background image and set `background-position: center center` ... – Hannes Jan 26 '12 at 17:01
  • @Hannes This was a perfectly valid question and can actually be done a number of different ways depending on exactly what he's trying to accomplish. – Eric Hodonsky Jan 26 '12 at 17:13
  • The OP apparently wants to center an image horizontally and vertically inside a DIV. – James P. Jul 22 '12 at 01:27

3 Answers3

2

Exactly Center an Image/Div Horizontally and Vertically

shaunsantacruz
  • 8,903
  • 3
  • 19
  • 19
2

Give this a go:

    div.wrapper{
      width:75px;
      height:75px;
    }
    img{
      width:50px;
      height:50px;
      display:block;
    /* For vertical center - margin: 0 auto;
       For horizontal center - margin: auto 0px;*/
      margin: auto auto;
    }
Eric Hodonsky
  • 5,617
  • 4
  • 26
  • 36
  • Unless mistaken, this will only work if you know the dimensions of a picture. – James P. Jul 22 '12 at 01:25
  • 1
    you're proposing a ludicrous scenario where the developers and designers of a project wouldn't be setting the sizes, or resizing uploads, and putting in zero back end work... never going to be a problem. – Eric Hodonsky Jul 26 '12 at 17:39
  • Sorry if you took the comment badly @Relic. This was just an observation and I'll upvote your comment for frankness. There is the case of user-uploaded images with variable proportions. Now you mention it, a back-end developer could manipulate images to add whitespace or transparency to fit given dimensions. – James P. Jul 27 '12 at 04:09
  • Oh so totally, and I hope you didn't think I was jumping down your throat... like you said, I was just being frank. I hope this helps answer future questions. – Eric Hodonsky Jul 30 '12 at 22:16
  • Sure. I should have added this link to go along with the comment: http://stackoverflow.com/questions/11597165/centering-dynamically-sized-images. Also, this adding whitespace has given me an idea to enhance an image-resizing script so thanks :) – James P. Jul 31 '12 at 03:40
1
background-position: center center;
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308