使用<a> and centering it vertically

时间:2017-01-22 19:45:08

标签: css

I'm trying to do a navigation bar using a table, here's the code right now:

.nav-bar a {
  display: block;
  height: 100%;
  width: 100%;
}
<table class="nav-bar" cellspacing="0">
  <tr>
    <td><a href="historia.htm">História</a>
    </td>
    <td><a href="local.htm">Localização</a>
    </td>
    <td><a href="direto.htm">Direto</a>
    </td>
    <td><a href="contactos.htm">Contactos</a>
    </td>
  </tr>
</table>

The problem is that the text gets sent upwards, like shown here填充空间。

3 个答案:

答案 0 :(得分:0)

为了在导航栏中垂直居中您的文字,我相信您要找的是将 line-height 设置为height。请注意,基于百分比的line-height与font-size相关。如果您未明确设置字体大小,则基于百分比的line-height将无效;)

.nav-bar a {
  display: block;
  height: 100%;
  line-height: 100%; /* relative to font-size */
  width: 100%;
}

希望这有帮助!

答案 1 :(得分:0)

您可以通过更改线条高度来垂直居中一行文字以填充垂直空间:

.nav-bar a {
  display: block;
  height: 100%;
  width: 100%;
  line-height: 100%;
}

答案 2 :(得分:0)

<强> 1。使用填充

.nav-bar a {
  display: block;
  padding: 15px 10px;
}

.nav-bar a:hover {
  background: lightgrey;
}

table {
  background: grey;
}
<table class="nav-bar" cellspacing="0">
  <tr>
    <td><a href="historia.htm">História</a></td>
    <td><a href="local.htm">Localização</a></td>
    <td><a href="direto.htm">Direto</a></td>
    <td><a href="contactos.htm">Contactos</a></td>
  </tr>
</table>

<强> 2。 Flexbox的
- 没有桌子

.nav-bar a {
  padding: 15px 10px;
}

.nav-bar a:hover {
  background: lightgrey;
}

.nav-bar {
  background: grey;
  display: flex; /* use inline-flex if you don't want it to strech the whole row */
}
<div class="nav-bar">
  <a href="historia.htm">História</a>
  <a href="local.htm">Localização</a>
  <a href="direto.htm">Direto</a>
  <a href="contactos.htm">Contactos</a>
</div>

<小时/> 在旁注中,如果您想要更准确的解决方案,请提供更多详细信息。你是否在导航栏中添加高度?你想让它拉伸整行,还是仅仅根据需要使用?