Html、CSS 垂直对齐菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10148629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Html, CSS vertical align a menu
提问by Reinard
I'm trying to make a menu, but I'm having trouble centering the text to the middle.
我正在尝试制作菜单,但无法将文本居中居中。
<div id="menucontainer">
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li> |
<li>@Html.ActionLink("About", "About", "Home")</li> |
<li>@Html.ActionLink("Projects", "Projects", "Home")</li> |
<li>@Html.ActionLink("Forum", "Forum", "Home")</li>
</ul>
</div>
#menu
{
background-image: url("../Content/img/bg-menu.png");
height:50px;
padding-left:30px;
padding-right:25px;
text-align:center;
border-radius:20px;
background-repeat:repeat;
display:block;
list-style: none;
margin-left:55%;
position:absolute;
color:#aa4dc6;
}
#menu li
{
display:inline;
padding:5px 10px 9px 10px;
}
#menu a
{
text-decoration:none;
color:#606060;
text-decoration:none;
text-transform:capitalize;
font-size:19px;
font-weight:bold;
font-family: 'Open Sans', sans-serif;
}
回答by Yaron U.
give it the same line-height
as the element's height
and the text should be properly aligned
使其与line-height
元素相同,height
文本应正确对齐
回答by James Johnson
There are a few solutions to this problem.
这个问题有几个解决方案。
Here's a jsFiddlethat demonstrates all of the solutions below.
这是一个jsFiddle,它演示了下面的所有解决方案。
First, you can try setting the display
property to table-cell
for the list items in the menu, and then you can use vertical-align:middle
to center the text.
首先,您可以尝试将display
属性设置table-cell
为菜单中的列表项,然后您可以使用vertical-align:middle
使文本居中。
The solution would probably work well, because instead of floating the list items, you can use CSS to make them behave like table cells.
该解决方案可能会奏效,因为您可以使用 CSS 使列表项的行为类似于表格单元格,而不是浮动列表项。
ul#menu {
display: table-row;
}
ul#menu li {
display: table-cell;
vertical-align: middle;
}
Second, you can set the line-height
property to the height of the list item. Be careful with this one though, because if the text wraps it will break the layout:
其次,您可以将该line-height
属性设置为列表项的高度。不过要小心这个,因为如果文本换行,它会破坏布局:
ul#menu li {
height: 30px;
line-height: 30px;
}
Lastly, instead of setting a fixed height, you can use padding to set the height of the list items. Assuming you use the same padding for the top and bottom, the text should be aligned in the center:
最后,您可以使用填充来设置列表项的高度,而不是设置固定高度。假设您对顶部和底部使用相同的填充,文本应该在中心对齐:
ul#menu li {
padding: 15px 5px 15px 5px;
}