如果child较小,则继承​​父宽度 - child定位为绝对值

时间:2013-11-25 20:50:13

标签: html css twitter-bootstrap

我正在为我的项目使用Twitter Bootstraps网格。 我有以下HTML:

<div class="row-fluid">
    <div class="span4 item">
        <div class="inner">Some text</div>
    </div>

    <div class="span4 item">
        <div class="inner">Some text</div>
    </div>

    <div class="span4 item">
        <div class="inner">Some text</div>
    </div>
</div>

和以下CSS:

.item {
    position: relative;
}

.item .inner {
    background: #fff;
}

.item:hover .inner,
.item .inner:hover { // I did them both because on mobile it catches only the first
    position: absolute;
}

结果是当我悬停“.item .inner”时,元素的长度与“.item”相同。 在“.inner”里面我可能有宽度未知的图像,我希望这些图像在鼠标悬停时伸展到它们的真实宽度 但因为“.item .inner”仅限于“.item”的宽度(可能是任何东西,取决于用户的屏幕)“.item .inner”不会拉伸。

我想也许可以从“.item”删除“position:relative”,这允许“.item .inner:hover”尽可能多地展开,但如果内容比“.item”的宽度短,它会缩小 - 这是一个我不想发生的功能

怎么可能实现呢?


编辑:

在第一种情况下,您可以看到我现在拥有的东西 - 当您悬停文本时,它会丢失其宽度 - 但如果您将图像悬停,它会拉伸。 http://jsfiddle.net/g5nP7/

在这种情况下,您可以看到,如果您悬停文本,它不会丢失它的宽度,但如果您将图像悬停,它将不会拉伸。 http://jsfiddle.net/dT7c5/4/

我想要的是当您悬停文本时 - 只有当内部内容比悬停时项目的宽度更长时,它才会延伸。 如果内容比项目

短,我不希望它缩小

正如您在两个示例中所看到的,如果您将图像悬停,它会失去它的高度并迫使其他项目上升。

1 个答案:

答案 0 :(得分:0)

我能提出的唯一纯CSS解决方案是使用max-widthmin-width的组合,在悬停时删除max-width。 Bootstrap使得它更难以使用,但实质上我删除了span4 CSS并使用媒体查询来实现非常相似的效果

... Some other CSS ...
.item .inner {
    ...
    width:auto;
}
.item:hover .inner, .item .inner:hover {
    max-width:none;
}
.span4.item { width:auto; }
@media screen and (min-width:980px) {
    .item .inner {
        min-width:265px;
        max-width:265px;
    }
}
@media screen and (max-width:980px) and (min-width:770px) {
    .item .inner {
        min-width:200px;
        max-width:200px;
    }
}

Demo here。它不是100%完美,因为它使用媒体查询断点而不是网格系统引导程序使用的那种(我尝试使用百分比宽度来模仿原始功能但它打破了它),但是对于媒体查询,很难区分它们。唯一的问题是,您可能希望为更大的屏幕添加另一个媒体查询,以使其更适合屏幕

相关问题