如何在 < ul > 中垂直对齐 < li > 元素?

我有一个水平的 <ul>,我需要在它的中心每个 <li>垂直。我的标记在下面。每个 <li>有一个边框,我需要的项目,以及他们的内容是在中间垂直。请帮帮忙,我是 CSS 的新手。


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
.toolbar li
{
border: solid 1px black;
display: block;
float: left;
height: 100px;
list-style-type: none;
margin: 10px;
vertical-align: middle;
}
.toolbar li.button
{
height: 50px;
}
</style>
</head>
<body>
<div class="toolbar">
<ul>
<li><a href="#">first item<br />
first item<br />
first item</a></li>
<li><a href="#">second item</a></li>
<li><a href="#">last item</a></li>
<li class="button"><a href="#">button<br />
button</a></li>
</ul>
</div>
</body>
</html>
418911 次浏览

I assume that since you're using an XML declaration, you're not worrying about IE or older browsers.

So you can use display:table-cell and display:table-row like so:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
.toolbar ul {
display:table-row;
}
.toolbar ul li
{
display: table-cell;
height: 100px;
list-style-type: none;
margin: 10px;
vertical-align: middle;
}
.toolbar ul li a {
display:table-cell;
vertical-align: middle;
height:100px;
border: solid 1px black;
}
.toolbar ul li.button a {
height:50px;
border: solid 1px black;
}
</style>
</head>
<body>
<div class="toolbar">
<ul>
<li><a href="#">first item<br />
first item<br />
first item</a></li>
<li><a href="#">second item</a></li>
<li><a href="#">last item</a></li>
<li class="button"><a href="#">button<br />
button</a></li>
</ul>
</div>
</body>
</html>

Here's a good one:

Set line-height equal to whatever the height is; works like a charm!

E.g:

li {
height: 30px;
line-height: 30px;
}

I had the same problem. Try this.

<nav>
<ul>
<li><a href="#">AnaSayfa</a></li>
<li><a href="#">Hakkımızda</a></li>
<li><a href="#">İletişim</a></li>
</ul>
</nav>
@charset "utf-8";


nav {
background-color: #9900CC;
height: 80px;
width: 400px;
}


ul {
list-style: none;
float: right;
margin: 0;
}


li {
float: left;
width: 100px;
line-height: 80px;
vertical-align: middle;
text-align: center;
margin: 0;
}


nav li a {
width: 100px;
text-decoration: none;
color: #FFFFFF;
}

You can use flexbox for this.

ul {
display: flex;
align-items: center;
}

A detailed explanation of how to use flexbox can be found here.