Centralize dropdown menu in css

Asked

Viewed 445 times

0

I searched the code needed to build a dropdown menu in CSS. What I found was a functional menu, but it was left-aligned. Then I looked for how to align elements to the center using CSS. I was able to center the menu, but the sublinks got weird, see in the image.

dropdown desalinhado

Since I chose a yellow background color for the menu on purpose. I will put here the CSS and HTML code:

HTML

<html>
<head>
<title></title>
</head>
<body>

<ul class="menu">
<li><a href="#">Home</a></li>
<li><a href="#">Link1</a>
   <ul>
   <li><a href="#">Sub1</a></li>
   <li><a href="#">Sub2</a></li>
   </ul>
</li>
<li><a href="#">Link2</a></li>
</ul>

</body>
</html>

CSS

body{
font-size:16px;
}

.menu{
list-style: none;
width: 25em;
background: yellow;
margin-left: auto;
margin-right: auto;
}

.menu li{
position: relative;
float:left;
}

.menu li a{
background: red;
color:#fff;
text-decoration:none; 
padding:14px 20px; 
display:block;
}

.menu li a:hover{
background:darkred; 
color: #fff; 
text-shadow:0px 0px 5px red; 
}

.menu li ul{
position: absolute;
top:45px;
left:0;
background-color: yellow;
display:none;
}  

.menu li:hover ul, .menu li.over ul{
display:block;
}

.menu li ul li{
border:1px solid #c0c0c0;
display:block;
width:100px;
}

OBS:

css is embedded in html as it is just a page with this menu...

Is the centering technique wrong? What can I do to center this menu?

  • 2

    Possible duplicate of How can I center my dropdown menu?

  • I used the recommended flex display, but the problem remains, this yellow bar on the left. I think the solution is to use left:-40 in the li ul menu and also remove background color from the menu.

2 answers

0

To center the menu, I used the flex display, which was suggested in the comments. The problem persisted, but I discovered it was due to a number of adjustments, for example the yellow background was not only in the . menu, I also adjusted position and width of sublinks boxes.

  • managed to solve?

  • yes, it was a functional menu and without those bugs, thank you.

-2

I managed to fix my putting position:relative and padding: 0px no . menu ul

Browser other questions tagged

You are not signed in. Login or sign up in order to post.