如何在可滚动的容器中将DIV水平拉伸到其内容?

时间:2015-10-16 13:53:58

标签: html css

我有一个可滚动容器内的项目列表。每个项目都应用了:hover样式。问题是如果容器滚动,那么背景会被裁掉,尽管内容完全可见。

如何让DIV延伸到内容的全宽,因此在悬停时它会完全突出显示?

这是Plunkr

您可以看到,当您水平滚动到大约一半然后将鼠标悬停在项目上时,只有部分内容变为红色:

cropped background



.box-container {
    white-space: nowrap;
    min-width: 100%;
    max-height: 100px;
    border:1px solid red;
    overflow: auto;
    cursor: pointer;
}
.item-container div:hover {
    background-color: red;
}

<div style="width:300px;">
    <div class="box-container">
        <div class="item-container">
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
        </div>
    </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

这听起来有点hacky,但有效。 table在内联和块级别之间表现,宽度由内容决定并强制换行。

.item-container div {
   display: table;
}

.box-container {
    white-space: nowrap;
    min-width: 100%;
    max-height: 100px;
    border:1px solid red;
    overflow: auto;
    cursor: pointer;
}
.item-container div {
    display: table;
}
.item-container div:hover {
    background-color: red;
}
<div style="width:300px;">
    <div class="box-container">
        <div class="item-container">
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
            <div>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</div>
        </div>
    </div>
</div>

答案 1 :(得分:0)

尝试在div上创建100vw

.item-container div {
  width:100vw;

}