简体   繁体   中英

Text not aligning to the center in the li ul

In the following code, through which I am trying to understand drop down menu. If you see the output, you can notice that the li texts FIRST SECOND AND FOURTH are not equally horizontally aligned with equal spaces between each other.For instance there is more horizontal space on the right side of FOURTH. Whats the best possible way to align the text in the middle (horizontally) without manually giving values of margin, padding etc. Like there should be a way using text-align:center or margin:auto auto that can align the text in the center automatically irrespective of the length of the text or font size.

  ul{ width:350px; height:50px; padding-left:0; margin:0; background:#CCCCCC; } ul > li{ list-style: none; display: inline; font-size: 24px; float: left; width: 106.66px; margin-right: auto; text-align: center; margin-left: auto; } ul > li > ul{ margin:10px 0px; padding-left:0; width:80px; height:40px; visibility: hidden; } ul > li > ul > li{ display:block; list-style-type:none; padding-left:10px; } ul > li:hover ul{ visibility:visible; } 
 <body> <ul> <li>First</li> <li> Second <ul> <li>Third</li> </ul> </li> <li>Fourth</li> </ul> </body> 

It because of your hidden ul. Don't use vissibility:hidden like that, it will make the ur hidden, right but it still take up space so it make your second li bigger than it normal should be - inspect element and you will see it - and it look like fourth li look in wrong place.

To prevent this, you can use display:none with position:absolute like my demo below; display:none make your third ul "disappear", make the ul look right, and with position:absolute, it prevent the fourth li run around (try delete the attribute position:absolute and you can see.

ul{
  width:350px;
  height:50px;
  padding-left:0;
  margin:0;
  background:#CCCCCC;
}
ul > li{
  list-style:none;
  display:inline;
  padding:10px 20px;
  font-size:24px;
  float:left;
  position: relative;
}
ul > li > ul{
  margin:10px 0px;
  padding-left:0;
  width:80px;
  height:40px;
  display:none;
  position:absolute;
}
ul > li > ul > li{
  display:block;
  list-style-type:none;
  padding-left:10px;
}
ul > li:hover ul{
  display:block
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM