【问题标题】:Centering image in div vertically and horizontally [duplicate]垂直和水平居中div中的图像[重复]
【发布时间】:2013-04-05 15:04:36
【问题描述】:

我想在一个 div 中垂直和水平居中一个图像,可以是各种大小。所有的图像都被制作成适合 div 的大小,但是它们的大小各不相同。

我该怎么做?

CSS:

.item-image-box {
    width: 48px;
    height: 48px;
    background-color: black;
    border-style: solid;
    border-color: #382418;
    border-width: 2px;
    border-right: 0;
    position: relative;
    float: left;
}

谢谢!

【问题讨论】:

  • 你知道div的高度吗?
  • 刚刚浏览了所有这些答案,没有一个有用。
  • 添加一个现场演示(使用像 jsfiddle.net 这样的网站)会很有帮助。图片标签本身是否应用了任何 CSS,例如 position:absolute? (看到容器有position:relative

标签: html css


【解决方案1】:

对于div

text-align: center;
line-height: /*height of your div*/

对于img

margin: auto;

【讨论】:

  • 它只是水平居中。 ://
  • @ShadyPotato 使 div 的 line-height 与其高度相同。
  • 谢谢。我刚刚意识到,vertical-alignment 只在表格布局的时代工作。
【解决方案2】:

背景

div {
       background: url(/path/to/img.png) no-repeat center center;
    }

display:table-cell 和 vertical-align: middle 方法

你也可以使用vertical-align: middle。

div {
   display: table-cell;
   vertical-align: middle;
   text-align: center;
}

http://jsfiddle.net/alexdickson/Vt5ed/

取自 CSS 技巧:

http://css-tricks.com/centering-in-the-unknown/

http://jsfiddle.net/chriscoyier/hJtpF/

【讨论】:

  • 图像会根据我输入的值(即来自数据库)而有所不同
  • 对于前景图像,position:absolute 方法仅在图像大小已知的情况下才有效,而事实并非如此。
  • 绝对位置方法也不起作用。不得不摆弄边距,然后当我将图像更改为更大的图像时,它没有居中。
  • 相当肯定你想要这个而不是:jsfiddle.net/chriscoyier/hJtpF
  • 还是不行。 ://
【解决方案3】:

只需使用背景定位和内联样式的力量。

JSfiddle:http://jsfiddle.net/F6PBJ/

HTML

<div style="background-image:url(http://placekitten.com/90/40)"></div>
<div style="background-image:url(http://placekitten.com/40/40)"></div>
<div style="background-image:url(http://placekitten.com/40/90)"></div>
<div style="background-image:url(http://placekitten.com/60/80)"></div>

CSS

div {
    width: 100px;
    height: 100px;
    background-color: black;
    background-position:center;
    background-repeat:no-repeat;
    border-style: solid;
    border-color: #382418;
    border-width: 2px;
    border-right: 0;
    float: left;
}

【讨论】:

  • 谢谢,效果很好。 :)