0

我有一个 500px 宽的图像。它在一个div里面。div的宽度是250px。如何对齐 div 内居中的图像?我应该使用top还是left应该有负边距?

4

4 回答 4

3

I would use negative margins: #myDiv img { margin: 0 -125px; }. This only works if you know the width of both the DIV and the IMG though.

于 2012-08-19T20:19:34.040 回答
0

演示

嘿,现在习惯了这样的display table-cell属性

<div class="parent">
<img src="http://www.gravatar.com/avatar/3c6597370b476903ed475f70b4b3ce31?s=32&d=identicon&r=PG">
</div>

CSS

.parent{
border:solid 1px red;
  display:table-cell;
  width:300px;
  height:300px;
  vertical-align:middle;
  text-align:center;
}
.parent img{
vertical-align:top;
}

演示

于 2012-08-20T07:11:49.993 回答
0

您可以在图像周围的 html 中更改(或至少添加)某些内容吗?这是一种古老的技巧,并且有点尴尬,因为它需要您<div>在图像周围添加额外的东西,但如果您对此表示满意,它会非常好用(注意,添加了一些边框以使效果更容易看到测试时):

<div style="width:250px; border: solid 2px red;">
    <!-- Place the following div at 50%: -->
    <div style="width: 500px; margin-left:50%; border: solid 2px blue;">
        <!-- ...then move the image back by half of it's own width: -->
        <img style="width:500px; margin-left:-250px; border: solid 3px green;" />
    </div>
</div>
于 2012-08-19T21:04:39.440 回答
0

试试这个(不确定 ie-6 但在 ie-7 和 plus 中可以正常工作)

<style>
.test{ height:250px; width:250px; overflow:hidden; position:relative;}
.test img{ position:absolute; top:50%; left:50%; margin-left:-250px; margin-top:-250px; height:500px; width:500px;}
</style>

<body>
<div class="test"><img src="img.png" alt="img" /></div>
</body>

如果可以使用该图像作为背景,你可以试试这个

.test{height:250px; width:250px; background:url(img-path.png) no-repeat 50% 50%;}
于 2012-08-20T12:10:01.280 回答