使用全宽排除溢出滚动条,其中“position:absolute” [英] Use full width excluding overflow scrollbar with "position: absolute"

查看:526
本文介绍了使用全宽排除溢出滚动条,其中“position:absolute”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个固定的顶部位置有一个小的红色div,在另一个有 overflow:scroll 的div。我希望jsFiddle清楚地表明: http://jsfiddle.net/mCYLm/2/

I would like to have a small red div with full width at a fixed top position, inside another div that has overflow: scroll. I hope the jsFiddle makes it clear: http://jsfiddle.net/mCYLm/2/.

问题是红色div与滚动条重叠。我想 right:0 表示 div.wrapper 的右边;它不会减去 div.main 的滚动条。当我将 overflow:scroll 移动到 div.wrapper 时,红色横幅具有正确的大小=http://jsfiddle.net/mCYLm/3/>小提示)。

The issue is that the red div is overlapping the scrollbar. I guess right: 0 means the right hand side of div.wrapper; it does not subtract the scrollbar of div.main. When I move the overflow: scroll into div.wrapper, then the red banner has the right size (fiddle). However, it is not at a fixed position anymore (scrolling down makes the banner scroll up).

如何一起实现以下两件事?

How can I achieve the following two things together?

  • The red banner is at the fixed position like in this fiddle.
  • The red banner has full width except the scrollbar like in this fiddle.

我想在Google Chrome中使用此工具。

I'd like to get this working in Google Chrome.

HTML:

<div class="wrapper">
    <div class="red-banner"></div>
    <div class="main">
        <div class="item">foo</div>
        <div class="item">foo</div>
        <div class="item">foo</div>
        <div class="item">foo</div>
    </div>
</div>​

CSS:

div.wrapper {
    position: relative;
}

div.main {
    height: 200px;
    overflow-y: scroll;
}

div.item {
    border: 1px solid black;
    margin: 20px;
    padding: 20px;
}

div.red-banner {
    background-color: red;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    height: 20px;
}


推荐答案

看起来不是可能是纯CSS,所以这里有一个JavaScript(jQuery)hack:

Seems like this isn't possible with pure CSS, so here's a JavaScript (jQuery) hack:

$(function() {
  var $container = $("<div>").css({ height: 1, overflow: "scroll" }).appendTo("body");
  var $child = $("<div>").css({ height: 2 }).appendTo($container);
  window.SCROLLBAR_WIDTH = $container.width() - $child.width();
  $container.remove();
});

然后:

$("div.red-banner").css({
  right: SCROLLBAR_WIDTH
});

这篇关于使用全宽排除溢出滚动条,其中“position:absolute”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆