将图像置于div内?

时间:2012-07-01 18:33:50

标签: css centering

我在div中有一个像这样的图像

<div><img /><div>

图像是动态的,没有固定的大小。 div的大小为200px by 200px。事先不知道图像尺寸。如果图片大小超过190px by 190px,请将其设置为190px by 190px(即max-width:190pxmax-height:190px)。如何满足这些需求,使图像居中?我也需要在Internet Explorer 7中使用的解决方案。

解决方案herehere无法应用于我的问题,因为

  1. 不确定图像是否小于200像素。

  2. 我也希望水平对齐。

  3. 没有Internet Explorer 7支持。

  4. (Stack Overflow上有一些关于相同问题的问题,但我的情况有所不同,所以它们不适用于这个特定问题。)

4 个答案:

答案 0 :(得分:6)

解决方案是将div更改为表格。通常情况下,您不应该使用表格进行定位,但是对于较旧的非标准兼容浏览器,有时候这是唯一的选择。 Demonstration here。对于记录,这也适用于Internet Explorer 6。

代码:

<强> 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>

这是使用CSS而不是将标记更改为实际表的update

#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>

答案 1 :(得分:2)

看到这个小提琴:http://jsfiddle.net/ANwmv/

按照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>

答案 2 :(得分:0)

为父级提供与其自身高度等效的 line-height ,以及中心的 text-align 属性。为图像提供中间的 vertical-align 属性,使其在行高中居中:

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

答案 3 :(得分:-1)

你可以这样做:

<div style="text-align:center;vertical-align:middle;"> 
    <img style="margin:0 auto" /> 
</div>
相关问题