3

我有一个绝对位于浏览器左上角 300 像素 x 300 像素的 div。我计划在 div 中显示一个图像,但不幸的是我不知道图像的大小,尽管我知道图像将是 300 像素乘 300 像素或更小。

如何创建一个设置宽度和高度为 300px 的 div 以水平和垂直居中相同大小或更小的图像?

4

2 回答 2

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

​jsFiddle 演示

于 2012-06-21T15:54:39.567 回答
6

在 div 上使用以下 CSS:

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>
于 2012-06-21T15:49:49.817 回答