在`< div>`中居中一个`< img>` [英] Center an `<img>` in a `<div>`

查看:138
本文介绍了在`< div>`中居中一个`< img>`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在包含< div> 的中心设置< img>

How do I center an <img> in a containing <div>?

通常 margin-left:auto; margin-right:auto; 无效。

图片可以大于容器, max-width max-height

The image can be larger than the container, and is scaled either horizontally or vertically by the max-width and max-height.

使用以下代码的jsfiddle: http://jsfiddle.net/9ShGj/1/

A jsfiddle with the below code: 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/

这篇关于在`&lt; div&gt;`中居中一个`&lt; img&gt;`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆