制作<a> tag fill </a> <li> <a> with display: table-cell

时间:2017-08-24 16:38:51

标签: html css html5 twitter-bootstrap css3

I want to make the anchor tag to fill the list element maintaining the text vertical and center aligned, but display: table-cell creates a padding on the top and bottom of the anchor, padding: 0 on the list doesn't work, display:block and height:100% on the anchor works but the text is pulled to the top.

Here's the JSFiddle

.header-menu {
  padding: 0;
  background: #fff;
}

.navbar .navbar-nav {
  width: 100%;
  display: table;
}

.navbar .navbar-nav .nav-item {
  display: table-cell;
  height: 70px;
  vertical-align: middle;
  border: 1px solid #000;
}

.navbar .navbar-nav .nav-link {
  padding: 0;
  color: #E90020;
  font-size: 14px;
  font-weight: 700;
  text-transform: uppercase;
  text-align: center;
  background: grey;
}

.todas-as-categorias-span {
  display: block;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

<nav class="navbar header-menu">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#">Item 1
        <span class="todas-as-categorias-span">Categorias</span>
        </a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Item 2</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Item 3</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Item 4</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Item 5</a>
      </li>
    </ul>
   </nav>

2 个答案:

答案 0 :(得分:2)

如果您希望灰色背景完全填满<li>个傻瓜,则必须将height: 100%放在<a>个元素上;你看到的白度不是填充物,它是不填充容器的元素。

现在,正如您自己写的那样,这将使您的文本与顶部对齐。但除非您需要支持超级旧浏览器,否则您只需使用flexbox进行居中即可。所以你需要的只是CSS中的5个新行:

.navbar .navbar-nav .nav-link {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    /* the rest of your original rules */
    padding: 0;
    color: #E90020;
    font-size: 14px;
    font-weight: 700;
    text-transform: uppercase;
    text-align: center;
    background: grey;
}

Updated JSFiddle

答案 1 :(得分:0)

该链接并不知道如何扩展它的高度以填充您已添加到LI元素的70px高度。

尝试:

.navbar .navbar-nav .nav-link {
    padding: 0;
    color: #E90020;
    font-size: 14px;
    font-weight: 700;
    text-transform: uppercase;
    text-align: center;
  background: grey;
  height: 100%;
}