使绝对定位的div容器匹配其内容的宽度

时间:2012-10-26 19:46:27

标签: html css slider css-float

我有一个CSS设置,我有一个PNG图像,绝对定位,有一个透明区域,作为一个窗口,一个div充满图像通过它后面显示。 div也是绝对定位的,它的内容是一系列浮动的图像,所以它们都在一行中。

问题是这个装满图像的div比容器宽得多,所以除非我指定图像容器div的宽度,否则图像都只是垂直叠加。我希望它们并排排列,但我不能为包含div的宽度编码一个值,因为它可以改变。我该怎么做呢?这是我的代码:

<div class="slider_box">
    <div class="slider_images">
        <img class="slider_image" src="img/share/recipes/pizza.jpg" alt="Pizza"/>
        <img class="slider_image" src="img/share/recipes/pizza.jpg" alt="Pizza"/>
        <img class="slider_image" src="img/share/recipes/pizza.jpg" alt="Pizza"/>
        <img class="slider_image" src="img/share/recipes/pizza.jpg" alt="Pizza"/>
        <img class="slider_image" src="img/share/recipes/pizza.jpg" alt="Pizza"/>
    </div> <!--images show through the slider mask, and should be floated left (or inline-block). Currently can't be side by side without specifying width of slider_images-->
    <img class="slider_mask" alt="Slider Mask" src="img/share_recipe_mask.png"/><!--sits on top of slider images -->
    <h4>Semolina <br/>Olive Oil Cake</h4> <!--sits on top of slider mask-->
</div>

.slider_box {
    width:190px; height:220px; position: absolute; overflow: hidden;
    .slider_images {
        position: absolute; bottom: 0;
        img { float: none; width: 190px; height:158px; }
    }
    .slider_mask { position: absolute; }
    h4 { .cubano; font-size:1.8em; position: absolute; color: #fff; top:11px; left:14px; line-height: 110%; }
}

CSS

.slider_box {
    width:190px; height:220px; position: absolute; overflow: hidden;
    .slider_images {
        position: absolute; bottom: 0;
        img { float: none; width: 190px; height:158px; }
    }
    .slider_mask { position: absolute; }
    h4 { .cubano; font-size:1.8em; position: absolute; color: #fff; top:11px; left:14px; line-height: 110%; }
}
.slider_nav {
    .slider_nav_btn { width:10px; height:10px; display:inline-block; .border-radius(50%,50%,50%,50%); color: #f3895f; }
    .slider_nav_btn:hover { color: @redDk; }
}

1 个答案:

答案 0 :(得分:0)

如果我正确掌握了这种情况,你需要容器​​的面积大小,对吗?

使用一点Javascript:

<div class="slider_box" id="easyID">
<!-- snip -->
<img class="slider_mask" id="easytoidentify" src="whatever" />
<script type="text/javascript">
  document.getElementById('easyID').style.width = document.getElementById('easytoidentify').width;
</script>

从那里,您只需要将overflow:hidden添加到“slider_box”css并定义“slider_images”的宽度,以便它足够宽。只要启用了Javascript,就可以了。