Center an image inside a div?

删除回忆录丶 提交于 2019-11-30 14:02:23

The solution is to change the div into a table. Normally, you shouldn't use tables for positioning, but when it comes to older non-standards-compliant browsers, sometimes that's the only choice. Demonstration here. For the record, this works on Internet Explorer 6, as well.

Code:

CSS

#theDiv
{
    width: 200px;
    height: 200px;
    text-align: center;
    vertical-align: middle;
}
#theImg
{
    max-width: 190px;
    max-height: 190px;
}​

​HTML

<table id="theDiv" style="border: solid 1px #000">
    <tr>
        <td>
    <img id="theImg" src="http://cdn1.sbnation.com/community_logos/9156/gangreen-small.jpg" />
        </td>
    </tr>
</table>

Here's an update that uses CSS instead of changing the markup to an actual table:

#theDiv
{
    display: table;
    width: 200px;
    height: 200px;
    text-align: center;
    vertical-align: middle;
}
#theImg
{
    max-width: 190px;
    max-height: 190px;
}

.tr {
  display: table-row;
}
.td { 
  display: table-cell;
  vertical-align: middle;
}

<div id="theDiv" style="border: solid 1px #000">
    <div class="tr">
        <div class="td">
    <img id="theImg" src="http://lorempixel.com/100/100/" />
        </div>
    </div>
</div>

See this fiddle: http://jsfiddle.net/ANwmv/

Solution to centering as suggested in: http://www.brunildo.org/test/img_center.html

<style type="text/css">
.wraptocenter {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    width: 200px;
    height: 200px;
    border: 1px solid red;
}
.wraptocenter img { max-width: 190px; max-height: 190px; }
.wraptocenter * {
    vertical-align: middle;
}
/*\*//*/
.wraptocenter {
    display: block;
}
.wraptocenter span {
    display: inline-block;
    height: 100%;
    width: 1px;
}
/**/
</style>
<!--[if lt IE 8]><style>
.wraptocenter span {
    display: inline-block;
    height: 100%;
}
</style><![endif]--> 

HTML:

<div class="wraptocenter"><span></span><img src="http://lorempixel.com/100/100" alt="..."></div>

Give the parent a line-height equivalent to its own height, and a text-align property of center. Give the image a vertical-align property of middle to centre it within its line-height:

HTML:

    <html>
        <body>
            <div>
                <img src="http://www.waleoyediran.com/wp-content/uploads/2011/04/stackoverflow.png"/>                
            </div>
        </body>   
    </html>

CSS:

div, img {
 border: 1px solid black;  
}

div {
  width: 200px;
  height: 200px;
  text-align: center;
  line-height: 200px;
}

img {
  max-width: 190px;
  max-height: 190px;
  vertical-align: middle;    
}

JS Fiddle example

Arian

You can do this:

<div style="text-align:center;vertical-align:middle;"> 
    <img style="margin:0 auto" /> 
</div>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!