3

I have a div that is absolutely positioned from the top left corner of the browser that is 300px by 300px. I plan to show an image in the div but unfortunately I do not know the size of the image although I do know that the image will be 300px by 300px or smaller.

How can I create a div that has a set width and height of 300px that centers images of the same size or smaller horizontally and vertically?

kapa
  • 77,694
  • 21
  • 158
  • 175
acidic
  • 1,497
  • 2
  • 19
  • 23

2 Answers2

7
#container { width: 300px; height: 300px; line-height: 300px; text-align: center; }
#container img { vertical-align: middle; display: inline-block; }

jsFiddle Demo

doptrois
  • 1,560
  • 11
  • 10
kapa
  • 77,694
  • 21
  • 158
  • 175
  • I didn't vote down but I got 2 down votes on the exact same answer 2 minutes ago :) Some people just like to be douches – Zoltan Toth Jun 21 '12 at 15:57
  • Just beware IE with inline-block if you want [IE7 support](http://quirksmode.org/css/display.html#inlineblock). – Robert K Jun 21 '12 at 15:58
  • @RobertK The `img` should be inline-block by default, and if you use a different element, there is still [the good old IE7 hack](http://stackoverflow.com/questions/6544852/ie7-problem-with-display-inline-block/6545033#6545033). – kapa Jun 21 '12 at 16:00
  • @ZoltanToth Yeah I see your deleted answer now. It is missing the `line-height`, but still, downvoting without a comment is not understable. – kapa Jun 21 '12 at 16:01
  • 1
    FYI : I had down voted his old answer because he didn't have the `line-height: 300px` - he deleted before I could comment. – iambriansreed Jun 21 '12 at 16:02
6

Use the following CSS on the div:

CSS

div {
    width: 300px;
    height: 300px;
    position: absolute;
    top: 0;
    left: 0;
    background: #fff center center no-repeat;
}

HTML / PHP

<div style="background-image: url('<?php echo $image_url; ?>');"></div>
iambriansreed
  • 21,935
  • 6
  • 63
  • 79
  • I would like to do that except that the image location is being created by PHP. Is there any way to do this while using PHP to generate the image link? – acidic Jun 21 '12 at 15:55
  • 2
    @acidic - See the second example. I would put the static CSS properties in the style sheet and only define the dynamic style property inline. – iambriansreed Jun 21 '12 at 15:57
  • @iambriansreed What's bad practice about the solution I posted? In my opinion [`img` vs. `background-image`](http://stackoverflow.com/questions/4335957/using-sprites-with-img-tag/4336431#4336431) should be decided on whether the image is considered content or decoration, not on which one is more practical to style. Btw I upvoted your solution. – kapa Jun 21 '12 at 18:00
  • My previous comment was a reply to a now removed comment, but I decided to leave it here because it might help future visitors to decide which technique to use in their situation. – kapa Jun 21 '12 at 19:42