【问题标题】:Extend "body" when absolute positioned element is outside the browser window当绝对定位元素在浏览器窗口之外时扩展“body”
【发布时间】:2023-03-24 08:41:02
【问题描述】:

想象一个像下面这样的 HTML 页面:

<body>
    <div class="main">
        <div class="free">aaa</div>
    </div>
</body>

free div 是绝对定位的,它的位置在浏览器可见区域之外。因此,它将产生溢出,并显示滚动条。没关系。

main div 应该与浏览器内的 full 区域一样大。不应仅限于可见区域。

html, body {
    height: 100%
}
.main {
    background-color: gray;
    width: 100%;
    height: 100%;
}
.free {
    position: absolute;
    width: 100px;
    height: 100px;
    left: 3000px;
    top: 3000px;
}

正如您在此处看到的,http://jsfiddle.net/y79NS/12/,灰色 div 没有在“溢出区域”中延伸。如果我向 html 和 body 元素添加静态宽度/高度,它会起作用,但我事先不知道它应该多大。

有纯 CSS 解决方案吗?如果不是,那么使用 Javascript 的最佳方法是什么,记住用户可以随时调整浏览器的大小?

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    你只是在你的 CSS 中缺少了一个分号,如果你想隐藏.free,也可以使用负边距:

    html, body {
        height: 100%;
    }
    body {
     position: relative;
    }
    .main {
        background-color: gray;
        height: 100%;
        width: 100%;
    }
    .free {
        position: absolute;
        width: 100px;
        height: 100px;
        left: -3000px;
        top: -3000px;
    }
    

    http://jsfiddle.net/btipling/y79NS/17/

    【讨论】:

    • 我需要“免费”的 div 位于那个位置:P 用户必须能够滚动并找到它。
    • 据我所知,您不能那样使用绝对定位。绝对定位将元素从流中取出。使.main 成为您希望该区域的高度和宽度,然后定位您的.free 而不是它。
    • 在这种情况下,最好将.mainmin-widthmin-height 设置为与.free 的位置匹配的值。像这样:jsfiddle.net/y79NS/25 注意缩小窗口会导致溢出,而​​.main 总是会覆盖这个溢出。唯一的问题是,如果.free 的位置是动态的,我必须从javascript 更新min-widthmin-height
    • 我不明白你想做什么。这是游戏吗?考虑在内存中而不是在文档状态中跟踪 x 和 y 坐标。使用游戏控件而不是滚动条。那么您就不必担心方钉圆孔类型的问题了。
    猜你喜欢
    • 1970-01-01
    • 2015-06-09
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多