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?
You can set the margin-top of the outer container object to the height of the floating div:
<div id="outerContainer">
... page content goes here ...
</div>
<div id="floatingNotification">
</div>
Then in css:
#floatingNotification
{
...
height: 20px;
}
#outerContainer
{
margin-top: 20px;
}
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:
$(document).ready(
function() {
var element = '<div id="notification"></div>';
var text = '<p>The text to show in the notification thingumabob.</p>';
$('div#wrap').prepend(element).find('#notification').prepend(text).css('display','none');
if ('#notification') {
$('div#notification').slideDown('slow');
}
}
)
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 the slideDown()
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.
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.