将固定宽度div内的动态宽度div居中

时间:2011-07-24 17:34:54

标签: html css position positioning

我对css有相当多的经验,甚至这个问题让我很难过。

我主题为Wordpress的NextGen图库插件,这意味着我无法控制HTML,我在尝试排列图像时遇到了问题。

在NextGen中,图像的最大尺寸为200px x 200px。图像是较大图像的缩略图,每个图像在尺寸和尺寸方面都有自己的约束,但都在200px x 200px以下

主要目标:
类图像是固定宽度,但其宽度根据其中的图像而变化。类imageBox环绕图像,其宽度固定为图像的最大宽度(200px宽,200px高)。对于宽度不是200px的图像,我希望它们在imageBox的中心排列。

NextGen Gallery生成的基本HTML:

<div class="imageBox">
   <div class="image">
      <img />
   </div>
</div>

到目前为止我的CSS:

.imageBox{
    width: 218px;
    height: 218px;
    float: left;
    position: relative;
    margin-top: 20px;
    margin-bottom: 20px;
    text-align: center;
}

.image{
    margin-right: 5px;
    text-align: center;
    position: absolute;
    bottom: 0px;
    display: inline-block;
}

我使用绝对定位来确保图像沿底边排列,因此底部:0px。

任何帮助都会很棒。

修改 搞砸了css,让课程错误。

4 个答案:

答案 0 :(得分:1)

试试这个:

.image{
    width: 218px;
    height: 218px;
    margin: 0 auto;
    position: relative;
    margin-top: 20px;
    margin-bottom: 20px;
    text-align: center;
 }

答案 1 :(得分:1)

这个简化的样本,如果你有指定的图像,它可以很好地工作:

<!doctype html>
<html>
<head>
    <title>Centered images</title>
    <style type="text/css">
        .imageBox
        {
            float: left;
            background: cyan;
            width: 200px;
            height: 200px;
            text-align: center;
            line-height: 200px;
        }
        img
        {
            vertical-align: middle;
            background: magenta;
            position: relative;
            bottom: 2px;
        }
    </style>
</head>
<body>
    <div class="imageBox">
        <img src="img.png" width="200px" alt="Image." />
    </div>
    <div class="imageBox">
        <img src="img.png" width="190px" alt="Image." />
    </div>
    <div class="imageBox">
        <img src="img.png" width="180px" alt="Image." />
    </div>
</body></html>

Internet Explorer 7和Opera之间存在较小的垂直2px差异。

这里的诀窍是使用vertical-align属性。它有点特殊,它与父元素上的line-height属性结合使用。

更多信息:

答案 2 :(得分:0)

我从未使用过wordpress,所以我不确定这些限制是什么;但是你可以用一个重要的标签覆盖他们的CSS吗?

.image{
    position: relative !important;
}

答案 3 :(得分:0)

解决方案是为图像类提供固定的200px宽度,并将其设置为绝对位置和底部0px。这使得它在捕获容器的整个宽度时捕捉到imageBox类的底部。

由于图像div现在位于底部和全宽,所需要的只是使图像居中,因此我将边距0px自动应用于图像&gt; img class,以图像为中心并解决我的问题。

可以看到here