How do I vertically align text inside an anchor el

2019-06-17 07:29发布

问题:

I have searched extensively and seen numerous examples on how to vertical-align text using the vertical-align property and the line-height property. However, all my efforts seem to bear no fruit as I am unable to get my text to align vertically. How do I do vertically align text to be centered? The height properties are not fixed so I can't use line-height.

HTML

<nav>
    <ul>
        <li><a href="html/login.html">Login</a></li>
        <li><a href="html/user_registration.html">Register</a></li>
        <li><a href="#">Programmes Offered</a></li>
    </ul>
</nav> 

CSS

nav
{
    height: 30%;
    width: 100%;
}

nav ul
{
    height: 100%;
    margin: 0px;
}

nav ul li
{
    height: 33%;
    width: 100%;
    vertical-align: middle;
}

回答1:

you may use a pseudo element displayed as an inline-box using full height of li and vertical-aligned to midlle. DEMO

body, html {
    height:100%; /* needed for demo */
}
nav {
    height: 50%; /* increased for demo */
    width: 100%;
}
nav ul {
    height: 100%;
    margin: 0px;
}
nav ul li {
    height: 33%;
    box-shadow:inset 0 0 0 1px; /* show me li , for demo */
}
nav ul li:before {
    content:'';
    height:100%;
    display:inline-block;
    vertical-align: middle;
}

edit

If you also reset display and vertical-align on <a>, links can be spread on a few lines (demo below):

body,
html {
  height: 100%;
}

nav {
  height: 70%; /* height set for snippet demo purpose, could be really too much  */
  width: 100%;
}

nav ul {
  height: 100%; /* will follow height, inherit height value , set in nav if any avalaible  */
  margin: 0px;
}

nav ul li {
  height: 33%;
  /* see me and my center*/
  box-shadow: inset 0 0 0 1px;
  background:linear-gradient(to top, rgba(0,0,0,0.1) 50%, rgba(0,0,0,0.2) 50%);
}

nav ul li:before {
  content: '';
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}

a {
  display: inline-block;
  vertical-align: middle;
}
<nav>
  <ul>
    <li><a href="html/login.html">Login</a>
    </li>
    <li><a href="html/user_registration.html">Register</a>
    </li>
    <li><a href="#">Programmes<br/> Offered</a>
    </li>
  </ul>
</nav>



回答2:

vertical-align aligns inline elements with their siblings.. unless used in a table cell.

I don't think there's a by-the-book way of vertically aligning.. but this should work:

D E M O

nav ul li
{
    background:#f1f1f1;
    height: 33%;
    width: 100%;
    border-top:1px solid #e0e0e0;
}

nav ul li a
{
    display:block;
    position:relative;
    top:50%;
    -webkit-transform:translate(0,-50%);
    -moz-transform:translate(0,-50%);
    transform:translate(0,-50%);

}


回答3:

Have you tried with

nav ul li a
{
    height: 33%;
    width: 100%;
    vertical-align: 5px; //(you can make it 10px or -10px, just so it fits your style)
}

Your text is within the a tag, so adding a in the css may solve your problem :)