简体   繁体   English

文字未对齐行中的中心

[英]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. 如果您看到输出,您会发现li文本FIRST SECOND AND FOURTH不是等间距地彼此等距对齐,例如在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. 什么是最好的可能的方式来在中间(水平)对齐文本,而无需手动给出边距,填充等值。就像应该有一种使用text-align:centermargin:auto auto可以将文本居中对齐自动,与文本的长度或字体大小无关。

  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. 这是因为您隐藏的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. 不要使用可见性:像这样隐藏,它将使您隐藏起来,对,但是它仍然占用空间,因此它会使您的第二个li大于正常值-检查元素,您将看到-看起来像第四个李看错地方了。

To prevent this, you can use display:none with position:absolute like my demo below; 为了防止这种情况,可以使用display:none和position:absolute,如下面的演示所示; 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. display:none使第三个ul“消失”,使ul看起来正确,并通过position:absolute防止第四个li跑来跑去(尝试删除属性position:absolute即可看到。

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 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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