微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

css – 如何垂直对齐锚点元素内的文本,该元素嵌套在无序列表中

我已经广泛搜索并看到了许多关于如何使用vertical-align属性和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;
}

解决方法

您可以使用显示为内联框的伪元素,使用li的全高和垂直对齐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;
}

编辑

如果您还重置了< a>上的显示和垂直对齐,则可以在几行上展开链接(下面的演示):

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.1) 50%,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>

原文地址:https://www.jb51.cc/css/214124.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。