so I am trying to figure the following issue: given a top nav bar with position fixed, is there a way that the following down section doesn’t get partially hidden by the navbar (because of the fixed position) by using "display: flex" and "align-items: center"? I know how to fix it by setting a margin-top equal to the height of the navbar to the section but I have seen that it can be also fixed in a more elegant manner by using display:flex and align-items:center and I would like to know if there is anybody who knows how to do that. I am attaching a codepen for the given situation. The problem is fixed with margin-top. Can you give an alternate solution to this issue using display: flex?
Here is the codepen code example:
https://codepen.io/buburuzza/pen/wvNWmBq
<div id="main">
<div id="navbar">
<ul style="display:inline-block;">
<li style="display:inline-block; margin:10px;">Home</l>
<li style="display:inline-block;margin:10px;">About</li>
<li style="display:inline-block;margin:10px;">Contact</li>
</ul>
</div> <!-- end navbar-->
<div class="container">
<div class="row" style="width:500px; margin:auto;">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed massa lectus, semper et diam et, finibus mattis orci. Aliquam volutpat dui ac quam sagittis, sed volutpat velit sollicitudin. Nullam at consectetur erat. Proin quis est pretium, volutpat tellus sit amet, lacinia ex. Nam vel massa sed dolor tincidunt imperdiet non quis lorem. Ut efficitur luctus vestibulum. Phasellus nec blandit turpis. Sed viverra quam vitae gravida tincidunt. Praesent interdum iaculis dolor, ac cursus quam semper sit amet. Ut sapien magna, vulputate at erat quis, congue fermentum tortor. Etiam neque ex, pellentesque at venenatis ac, sollicitudin ut quam.
</p>
</div>
</div>
</div> <!-- end main -->
body {
width:100%; margin:0; padding:0;
}
#main {
width:100%;
height:auto;
margin:0;
padding:0;"
}
#navbar{
display:block;
margin:0;
padding:0;
position:fixed !important;
height:60px;
background-color:grey;
width:100%;
top:0;
}
.container {
display:flex !important;
height:100%;
align-items: center !important;
background-color:yellow;
width:100%;
height:auto;
margin-top:60px; /* HERE */
}
2
Answers
You can achieve the desired layout without using the
margin-top
property by using flexbox. Here’s an alternative solution usingdisplay: flex
andalign-items: center
:CSS:
In this solution, I’ve used flexbox for both the
#navbar
and.container
. The#main
element is set todisplay: flex
with a column direction to stack the#navbar
and.container
vertically. Thealign-items: center
on both#navbar
and.container
ensures that the content is vertically centered, and you don’t need to usemargin-top
.Just use
for the navbar and you won’t need any margin.