Center an `<img>` in a `<div>`

柔情痞子 提交于 2019-12-24 19:20:05

问题


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

The usual margin-left: auto; margin-right: auto; isn't working.

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

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;
}

回答1:


You can write like this:

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>

Check this http://jsfiddle.net/dP89y/




回答2:


Image is not a block level element so need to convert it into block level element

So in your css add

.container img {
 display:block                /*ADD this line*/
 max-width: 200px;
 max-height: 200px;
 margin-left: auto;
 margin-right: auto;
 vertical-align: middle;
}

Also you need to consider following points

Doctype : check whether it is not in quirks mode.

Width of inner div or image must me less that width of parent div.

do check these things you will get your answer...All the best.




回答3:


Unless you are making the img a block level element, you should be able to center it with:

.container { text-align: center; }



回答4:


Update following CSS... vertical-align:middle; text-align:center

   .container {
        width: 200px;
        height: 200px;
        background: rgb(120, 120, 120);
        border: 1px solid red;
        margin: 5px;
        vertical-align:middle; text-align:center //add this
    }


来源:https://stackoverflow.com/questions/13757783/center-an-img-in-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!