I'm creating a basis for a navigation bar. The menu can have multiple submenus within it. When a menu item with a submenu is clicked on the subMenu appears below. I have it mostly working except the nav doesnt take up the full width of the screen. When I try to center it the submenus break. I don't fully understand what I'm doing and I need some help understanding what is going on here and how to solve it. Thank you for any help given.
The menu for better understanding
nav {
display: flex;
font-weight: bold;
}
div {
display: inline-block;
}
li {
list-style: none;
}
li:not(.subMenu){
padding: 10px 20px;
}
.dropdown {
position: absolute;
}
<header>
<nav>
<ul>
<div>
<li id="About Me">About Me</li>
<ul >
<li id="Test" >Test</li>
<li id="Test2" >Test2</li>
</ul>
</div>
<div>
<li id="Projects">Projects</li>
</div>
<div>
<li id="Temp">Temp</li>
</div>
<div>
<li id="Helloooo">Helloooo</li>
<ul >
<li id="Test44" >Test44</li>
</ul>
</div>
</ul>
</nav>
</header>
edit: removing "display: flex" or attempting to use justify-content or align-items appears to do nothing
CodePudding user response:
Here you go...
The main problem was with positioning. If you want a child to have position: absolute;
, you need to set position: relative;
to the parent. Other than that, a little bit of CSS needs to be added.
nav {
display: flex;
font-weight: bold;
}
ul {
width: 100%;
display: flex;
justify-content: center;
}
ul > div {
display: inline-block;
}
li {
list-style: none;
display: block;
text-align: center;
}
li:not(.subMenu) {
padding: 10px 20px;
}
.dropdown {
display: block;
padding: 0;
}
#wrapper {
position: relative;
}
#test,
#test2,
#test44 {
position: absolute;
}
<header>
<nav>
<ul>
<div id="wrapper">
<li id="About Me">About Me</li>
<ul >
<li id="Test" >Test</li>
<li id="Test2" >Test2</li>
</ul>
</div>
<div id="wrapper">
<li id="Projects">Projects</li>
</div>
<div id="wrapper">
<li id="Temp">Temp</li>
</div>
<div id="wrapper">
<li id="Helloooo">Helloooo</li>
<ul >
<li id="Test44" >Test44</li>
</ul>
</div>
</ul>
</nav>
</header>
CodePudding user response:
You have it in flexbox so you need to specify position of container. Something like
nav {
display: flex;
justify-content: center;
font-weight: bold;
}
CodePudding user response:
You need to give display flex to ul tag inside the nav tag because nav has only one child that is
then give justify-content: center
to tag and it will center all the children
CodePudding user response:
Thanks to @Cervus camelopardalis for his answer which helped
Here is my solution, no changes to html but changed the css to:
nav {
display: flex;
font-weight: bold;
}
ul {
width: 100%;
display: flex;
justify-content: center;
}
li {
list-style: none;
text-align: center;
}
li:not(.subMenu){
padding: 10px 20px;
}
.dropdown {
display: block;
padding: 0;
}