2013-11-21 50 views
0

我有两个不同的宽度和高度的图像,需要在图像框中居中定位。这里是HTML和CSS的例子。如何使用css定位不同大小的图像?

<div class="box"> 
    <div class='image'> 
     <img alt="" src="image.jpg"/> 
    </div> 
</div> 

.box { 
    max-width: 970px; 
    height: 440px; 
} 
.box img { 
    max-width: 100%; 
    position: absolute; 
    bottom: 8px; 
    margin-left: auto; 
    margin-right: auto; 
} 

此代码适用于精确宽度和高度的大图像。但是当一个较小的图像放置在图像框中时,该图像位于右下角。我怎样才能使两个图像中心底部?

感谢任何人的帮助!

回答

0

在这里,你去...我会尽力解释,因为我们去,但简短的回答,a fiddle

.box { 
    /* Just so I could see the parent */ 
    background-color: #bada55; 
    max-width: 970px; 
    height: 440px; 
    /* Needed to make this element positional (so it will contain the absolutely positioned child */ 
    position: relative; 
    /* Yep, center wasn't necessary here... */ 
} 
.box .image { /* move this to the image wrapper */ 
    position: absolute; 
    bottom: 8px; 
    /* Force full width */ 
    left: 0; 
    right: 0; 
    /* Center contents (the image) */ 
    text-align: center; 
} 
img { 
    max-width: 100%; 
} 
+0

谢谢菲利普斯。这很好。但是,我忘了提及该图像是在外部html文档的iframe中,该文档的固定宽度为989 x 600,并且您编码图像的位置居中正确,但在.box内不在iframe内:(在我发布这个问题之前,我忘了提及这个问题,因此,我所做的是将.box的高度设置为495px,并且这种方式将图像相对于iframe进行了定位,你会怎么做? –

+0

因此,如果结构是iframe> .box> .image> IMG只是采取的立场:相对关闭.box。 – philwills

+0

是的。它工作得很好!谢谢菲利普斯!非常感谢。 –

0

我发现这招语义工作得很好(没有任何绝对位置)

.box { 
margin: 0; 
text-align: center; 
max-width: 970px; 
height: 440px; 
border:2px solid red; 
} 

.box .something-semantic { 
display: table; 
width: 100%; 
height: 100%; 
} 

.box .something-else-semantic { 
display: table-cell; 
text-align: center; 
vertical-align: bottom; 
} 

HTML

<div class="box"> 
<div class="something-semantic"> 
<div class="something-else-semantic"> 
    <img src="" width="50" height="40"/> 
    <img src="" width="120" height="70"/> 
</div> 
</div> 
</div> 

fiddle here.

+0

这基本上是使用表来格式化...即使你没有使用表标记,你基本上使该div与表的样式(比使用表,但仍然不好)。 – philwills

+0

谢谢@buddweeze! –

相关问题