简体   繁体   中英

Vertical alignment of text in li

I've been fooling around with HTML/CSS recently, and I'm trying to vertically align the text in an li so that it is in the center. I've seen this question (or some variation of it) asked a bunch of times, so I apologize in advance for asking a question I'm sure you're tired of seeing, but I can't get any of the suggested solutions to work. I'm also trying to avoid setting a specific height / line-height for the li , since I'd like this to adjust to the size of the screen.

Here's the HTML:

<ul id="nav">
    <li><a href="">Home</a></li>
    <li><a href="">About</a></li>
    <li><a href="">Experience</a></li>
    <li><a href="">Contact</a></li>
</ul>

Here's the CSS:

#nav {
    position: absolute;
    width: 100%;
    height: 100vh;
    top: 0;
    left: 0;
    list-style: none;
    padding: 0;
    margin: 0;
}

#nav li {
    text-align: center;
    height: 25%;
    width: 100%;
    margin: 0 auto;
}

#nav li a {
    display: block;
    height: 100%;
}

#nav li a:hover {
    background: #ccc;
}

I also have this fiddle set up in case you'd like to mess around with it and see if you can get it working. Thanks!

You can just make the line-height of #nav li 25% of the viewport height like so

#nav li {
 text-align: center;
 height: 25%;
 width: 100%;
 margin: 0 auto;
 line-height: 25vh; /* this is the only thing you need to add */
}

It's very simple and short and will work with any changes to the text (like font-size etc) or the list. It doesn't matter how many items you add or remove from the list or what changes you make to the height of the #nav or its list items. See the first working revision of your jsFiddle ;)

Set display: table; on your li and

display: table-cell;
vertical-align: middle;

on your a

final styles:

#nav li {
    display: table;
    text-align: center;
    height: 25%;
    width: 100%;
    margin: 0 auto;
}

#nav li a {
    display: table-cell;
    height: 100%;
    vertical-align: middle;
}

Rev 6 of your fiddle

Try these changes in your css

#nav li {
    text-align: center;
    height: 25%;
    width: 100%;
    margin: 0 auto;
    display: table;  /* added */
}

#nav li a {
    display: table-cell;  /* changes from block to table-cell */
    vertical-align: middle;  /* added */
    height: 100%;
}

See the working example here http://jsfiddle.net/t6ryfqzk/7/

Try making your li an inline-block if you want them next to eachother, or as block if you want them underneath eachother. Make sure you give the li elements a fixed width, and set their text-align as centered .

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.

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