html - 将 `<img>` 置于 `<div>` 的中心

标签 html css margin vertical-alignment

如何将 <img> 居中?在包含<div>

通常margin-left: auto; margin-right: auto;不工作。

图像可以比容器大,并由 max-width 水平或垂直缩放。和 max-height .

带有以下代码的 jsfiddle:http://jsfiddle.net/9ShGj/1/

HTML:

<div class="container">
   <img src="http://www.yensa.com/fat/fat-dude10.jpg" />
</div>
<div class="container">
   <img src="http://oi43.tinypic.com/bje2wn.jpg" />
</div>

CSS:

.container {
 width: 200px;
 height: 200px;
 background: rgb(120, 120, 120);
 border: 1px solid red;
 margin: 5px;
}

.container img {
 max-width: 200px;
 max-height: 200px;
 margin-left: auto;
 margin-right: auto;
 vertical-align: middle;
}

最佳答案

你可以这样写:

CSS

div{
    width:200px;
    height:200px;
    border:1px solid red;
    text-align:center;
    line-height:200px;
}

img{
    vertical-align:middle;
}

HTML

<div>
    <img src="http://dummyimage.com/150x150/000/fff&text=dummy" >
</div>

检查这个http://jsfiddle.net/dP89y/

关于html - 将 `<img>` 置于 `<div>` 的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13757783/

相关文章:

html - Flex 方向列,但其中两个子项彼此相邻,桌面顺序不同

javascript - polymer 下拉列表问题

html - 文本没有采用我在 css 文件中指定的字体样式

css - 使用 CSS 在链接后添加图像在 Firefox 和 IE 中不起作用

css - margin 不推低另一个 margin

html - IE6 + IE7 CSS 溢出问题 : hidden; - position: relative; combo

jquery - 如何使用 jquery/ajex 为 phonegap 解析 "Remote "xml 文件?

html - CSS 溢出在 Chrome 中不起作用

css - 如何摆脱溢出的 div 行之间的垂直边距?

android - 将边距设置为 ListView 项目,而不影响整个 ListView 的边距