I have a horizontal <ul>
and I need to center each <li>
in it vertically. My markup is below. Each <li>
has a border, and I need the items as well as their contents to be in the middle vertically. Please help; I am new to 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>
Inorder to make vertical-align: middle; work, you need to use display: table; for your ul element and display: table-cell; for li elements and than you can use vertical-align: middle; for li elements. You don't need to provide any explicit margins , paddings to make your text vertically middle.
(This is an old question, I know) There are two scenarios here: 1) if you want the text alignment to be center, then use text-align: center on the ul ; but if you want the list itself to be centered on the screen with the text still left aligned, then define a width or max-width property and add margin-left: auto; ...
If the inner element can have a fixed height, you can make its position absolute and specify its height , margin-top and top position. jsfiddle example. If the centered element consists of a single line and its parent height is fixed you can simply set the container's line-height to fill its height.
As a way of doing this, you could make use of flexbox and simply give the <li> a display:flex and align-items:center . That will vertically center all the elements inside of them.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With