绝对定位元素不会填充容器宽度

时间:2015-09-17 10:43:17

标签: javascript html css

我有一条红线,我想在滚动的div中水平拉伸:



 
.p
{
    background-color: blue;
    overflow: auto; /* so that scrollbar appears */
    position: relative; /* this is required by the absolute positioning of the line */
}

.box
{
    background-color: red;
    width: 100px;
    height: 100px;
    margin-left: 3000px; /* such that horizontal scrollbar appears */
}

.line{
    border-top: 1px dashed red; 
    position: absolute; 
    left: 0; 
    right: 0;
    top: 50px; 
}

<div class='p'>
    <div class='box'></div>
    <div class='line'></div>
</div>
&#13;
&#13;
&#13;

问题是滚动后线条不会伸展。

为什么没有工作以及如何解决这个问题?

如果可能的话,显然不会使用不使用JavaScript的解决方案。

更新: 小提琴: http://jsfiddle.net/mwznLh1p/

5 个答案:

答案 0 :(得分:1)

我希望这会对你有所帮助。

如果不让我知道,可以有更好的解决方案。

 .p {
            background-color: blue;
            overflow: auto;
            /* so that scrollbar appears */
            position: relative;
            /* this is required by the absolute positioning of the line */
        }

        .box {
            background-color: red;
            width: 100%;
            height: 100px;
            margin-left: 3000px;
            /* such that horizontal scrollbar appears */
        }

        .line {
            border-top: 1px dashed red;
            overflow: auto;
            position: fixed;
            width: 100%;
            top: 50px;
        }

答案 1 :(得分:0)

尝试使用position:fixed;

 .line {
    border-top: 1px dashed red;
    position: fixed;
    left: 0;
    right: 0;
    width: 100%;
    top: 50px;
}

答案 2 :(得分:0)

初看起来我会添加.line {width:3000px}(等于margin-left)并删除{right:0}。我还将线条添加为黄色,并看到它与红色框不重叠

 
.p
{
    background-color: blue;
    overflow: auto; /* so that scrollbar appears */
    position: relative; /* this is required by the absolute positioning of the line */
}

.box
{
    background-color: red;
    width: 100px;
    height: 100px;
    margin-left: 3000px; /* such that horizontal scrollbar appears */
}

.line{
    border-top: 1px dashed yellow; 
    position: absolute; 
    left: 0; 
    width: 3000px;
    top: 50px; 
}
<div class='p'>
    <div class='box'></div>
    <div class='line'></div>
</div>

答案 3 :(得分:0)

您可以将width提供给该行..

.line{
    border-top: 1px dashed red; 
    position: absolute; 
    left: 0; 
    width: 1000px;
    top: 50px; 
}

答案 4 :(得分:0)

只需改变这两行:

line{
    left: -9999px; 
    right: -9999px;
}