下推网页内容
我将一个 div 浮动到窗口顶部。但是,它覆盖了页面顶部的内容,也就是说,它没有向下推页面的最顶部。然而我看到 Stack Overflow 通过他们的通知栏执行此操作,因为它没有覆盖用户名/代表/链接。有什么方法可以用 CSS 复制这个吗?
I'm floating a div to the top of the window. However, it's covering the content at the top of the page, that is, it's not pushing down the very top of the page. Yet I see Stack Overflow doing this with their notification bar, because it's not covering the username/rep/links. Is there a way I can replicated this with CSS?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将外部容器对象的 margin-top 设置为浮动 div 的高度:
然后在 css 中:
You can set the margin-top of the outer container object to the height of the floating div:
Then in css:
就 Stack Overflow 而言,我认为他们很有可能使用 jQuery 来操作页面内容。我还没有研究过链接的脚本,也没有收到任何通知来检查,但我大胆猜测它是这样的:
请注意,我对 jQuery 非常陌生 - 坦率地说,JavaScript总的来说——所以我很有可能提出了一些可怕的错误建议。但是,经过测试,这个概念是有效的。即使您要添加的
元素
是浮动的或绝对定位的,slideDown()
似乎也会负责移动页面内容,以避免它覆盖其他元素。不过,这可能是我的设置中的巧合,也可能不是。
In the case of Stack Overflow, I think there's a good chance that they're using jQuery to manipulate the page contents. I haven't explored the linked scripts, and I've not got any notifications to check with, but I'd hazard a guess that it's something like:
Please be aware that I'm incredibly new to jQuery -and, frankly, JavaScript in general- so there's every chance that I've suggested something hideously wrong. But, having tested it, the concept works. Even if the
element
you want to add is floated or absolutely positioned theslideDown()
seems to take care of moving the page contents in order to avoid it covering up other elements.This may, or may not, be some coincidence in my set-up, though.
这个问题的答案取决于您使用的是相对定位浮动还是绝对定位浮动。如果是绝对的,请将浮动 div 设置为例如 {top: 20px;}。如果是相对的,请使用 padding-top、margin-top (或在其上方的元素上使用 margin-bottom)。
在常见浏览器中哪种效果最好取决于整体情况。
The answer to this depends on whether you're using a relative or absolute positioned float. If it's absolute, set your float div to for example {top: 20px;}. If it's relative, use either padding-top, margin-top (or margin-bottom on an element that's above it).
What works best across the common browsers depends on the overall picture.