sklrboy sklrboy - 6 months ago 22
CSS Question

How to prevent the page loosing the height of fixed navbar and slipping under it in top position?

I'm working on a fixed navbar, which stays at the top of the screen while scrolling, but when I give my navbar the

position:fixed
attribute, the rest of the content slips under it and my page looses the navbar's height. To be more specific, my navbar is 80px tall and when I change into fixed, the marquee (the following div) qoes 80px higher under the navbar. I have resolved it with kind of a "quick fix", adding and extra
nav-background
div with the height of my navbar to the top of my page, so it seems like my navbar doesn't float above anything in top position, but how can I resolve the case with a "professional" method?



#navbar {
margin:0px;
height:80px;
width:100%;
z-index:103;
background-color:rgba(255,255,255,.8);
position:fixed;
}

#logo {
display:inline-block;
float:left;
padding: 15px 0px 15px 0px;
margin-left:100px;
}

#logo_img {
max-height:50px;
}

#anchor-links {
display:inline-block;
float:right;
height:80px;
padding: 15px 0px 15px 0px;
margin-right:150px;
}

.nav li {
display:inline-block;
}

.nav a {
text-decoration:none;
color:#6f8595;
font-size:16px
}

#nav-background {
height:80px;
}

.marquee {
border:1px solid red;
font-size:16px;
height:630px;
width:100%;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<div id="navbar">
<div class="row">

<div id="logo" class="logo">
<a href="index.html"><img id="logo_img" src="img/yoursite_logo.png" alt="YourSite Logo"></a>
</div>

<div id="anchor-links">
<ul class="nav">
<li><a data-scroll href=".marquee">Home</a></li>
<li><a data-scroll href="#about">About</a></li>
<li><a data-scroll href="#services">Services</a></li>
<li><a data-scroll href="#portfolio">Portfolio</a></li>
<li><a data-scroll href="#footer">Contact</a></li>
</ul>
</div>

</div>
</div>
<div id="nav-background" class="clearfix"></div>
<div class="marquee"></div>




Answer

When you position a div as fixed it is taken out of the regular document flow. Because of this, there is no other way of compensating for its height than setting one or multiple properties on elements that are still taken into account with regard to document flow when the browser renders the page.

The solution you came up with actually works fine, and there's nothing wrong with it.

However, you should be able to get a similar result by adding a padding-top: 80px; to .marquee, saving you the trouble of one extra div that only serves stylistic purposes. This results in the padding-box of .marquee slipping under the header, but its content should align nicely below the header.