Ok, here's the code for making web responsive navbar using flexbox. My question comes out of pure curiosity since I'm a newbie and just learning html&css and would like to understand the logic behind it:
Why is it necessary to give display: flex both to .navbar and its child .navbar ul class? To display flex, we need to add it to a parent element, in this case it's nav. Why won't it work like that, why is it necessary to add display: flex to its direct child .navbar ul as well? Thanks!
<nav class="navbar">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About me</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact me</a></li>
</ul>
</nav>
.navbar {
display: flex;
justify-content: center;
align-items: center;
background-color: rgb(0, 0, 0, 0.5);
position: sticky;
top: 0;
border: 3px dotted red;
}
.navbar ul {
display: flex;
margin: 20px 0px;
border: 3px dotted blue;
}
The .navbar
centers the ul
(i.e. the links) in this case, due to its flex settings (horizontally and vertically).
On the ul
the flex setting here only makes sure the li
s are arranged horizontally - not necessarily a typical flex example.
I would add some details, especially padding or margins on the list items (see below) and list-style-type: none;
on the ul
to hide the default dots before the li
s.
.navbar {
display: flex;
justify-content: center;
align-items: center;
background-color: rgb(0, 0, 0, 0.5);
position: sticky;
top: 0;
border: 3px dotted red;
}
.navbar ul {
display: flex;
margin: 20px 0px;
border: 3px dotted blue;
list-style-type: none;
}
.navbar li {
padding: 10px 20px;
}
<nav class="navbar">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About me</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact me</a></li>
</ul>
</nav>