I'm trying to create a simple CSS menu. Here are the constraints:
Here is the html:
<ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
</ul>
Here are my attempts, each has its own failing.
http://jsfiddle.net/QzYAr/266/ (widths aren't expressed as a %)
ul { width: 600px; display: table; table-layout: fixed; background: #EEE; } li { float: left; border: 1px dotted red; } a { display: table-cell; height: 50px; vertical-align: middle; text-align: center; width: 150px; border: 1px dotted green; }
http://jsfiddle.net/RzeK2/ (Anchor tag doesn't fill height)
ul { width: 80%; display: table; table-layout: fixed; background: #EEE; } li { float: left; border: 1px dotted red; } a { display: table-cell; height: 50px; vertical-align: middle; text-align: center; width: 150px; /*this is the part that needs work?*/ border: 1px dotted green; }
http://jsfiddle.net/XsLHY/ (Anchor tag text isn't vertically centered)
ul { width: 80%; display: table; table-layout: fixed; background: #EEE; } li { display: table-cell; width: 33%; height: 50px; vertical-align: middle; text-align: center; border: 1px dotted red; } a { display: block; border: 1px dotted green; height: 50px; }
http://jsfiddle.net/w55Lg/ [suggested by two answers below] (Creates ugly button if text wraps, and also other buttons aren't full height now)
same as three, plus: a { line-height: 50px; }
Try this:
ul {
width: 80%;
background: #EEE;
}
li {
width:33.33333333%;
float:left;
}
a{
display:block;
text-align:center;
height:50px;
line-height:50px;
}
a:hover {
background:red;
}
DEMO: http://jsfiddle.net/QzYAr/267/
EDIT: If you have longer text, you can wrap it inside a <span>
tag and add this CSS:
ul span{
display:inline-block; vertical-align:middle;
line-height:14px;
}
Using fiddle #2, updated version: http://jsfiddle.net/XsLHY/1/
You just need to add a matching line-height to the li
as the height of the a
.
CSS
ul {
width: 80%;
display: table;
table-layout: fixed;
background: #EEE;
}
li {
display: table-cell;
width: 33%;
height: 50px;
vertical-align: middle;
text-align: center;
border: 1px dotted red;
line-height: 50px;
}
a {
display: block;
border: 1px dotted green;
height: 50px;
}
To fix the anchor problem, you can switch the order, so the <a>
wraps the <li>
instead of the other way around:
<ul>
<a href="#"><li>Item 1</li></a>
<a href="#"><li>Item 2</li></a>
<a href="#"><li>Item 3</li></a>
</ul>
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.