css - 在 flexbox 布局中垂直居中链接文本

标签 css

我有一个由 5 个链接组成的菜单。我需要每个链接都是可用宽度的 33%,链接之间有间距。水平和垂直间距必须相同。

链接的高度必须与该行中最高的链接相同,即使链接文本的长度会因链接而异。理想情况下,所有链接的高度都相同,但我怀疑这是可能的。

链接文本是动态的,会发生变化。这适用于响应式网站,因此页面宽度会有所不同。

我根本无法更改 HTML。

这是一个仅限移动设备的网站,因此我无需担心较旧的浏览器。我应该可以使用 flexbox。

<ul>
    <li>
        <a href="#">
            <span>Link 1</span>
        </a>
    </li>
    <li>
        <a href="#">
            <span>Link 2 has much longer text than the other links</span>
        </a>
    </li>
    <li>
        <a href="#">
            <span>Link 3</span>
        </a>
    </li>
    <li>
        <a href="#">
            <span>Link 4</span>
        </a>
    </li>
    <li>
        <a href="#">
            <span>Link 5</span>
        </a>
    </li>
</ul>

我的以下代码在 Chrome 中运行良好。我唯一还需要做的就是将链接文本垂直居中(见下图)。

align-items: center 属性看起来很有前途,但是如果我将它应用于 ul,则 lis 不再具有相同的高度。

*, *:before, *:after {
    -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;
 }

ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-wrap: wrap;
  width: 50%;
  border: 2px solid black;
  margin: auto;
}

li {
  list-style-type: none;
  float: left;
  width: 32%;
  background: grey;
  text-align: center;
  overflow: hidden;
  margin-bottom: 2%;
  vertical-align: middle;
}

li:nth-of-type(2),
li:nth-of-type(5)
{
  margin-left: 2%;
  margin-right: 2%;
}

a {
  display: inline-block;
  margin: -10em;
  padding: 10em;
}
a {
  background: gold;
}
a:hover {
  background: green;
}

http://codepen.io/anon/pen/CeiqK

enter image description here

最佳答案

我不知道我在这里发布的这个解决方案是否对您有效。不管怎样,我稍微改变了你的 css 来得到它:

ul {
  margin: 0;
  padding: 0;
  width: 50%;
  border: 2px solid black;
  margin: 0 auto;
  font-size: 0;  /* this fix inline-block margins */
}

li {
  font-size: 14px;
  list-style-type: none;
  display: inline-block;
  width: 32%;
  min-height: 34px;
  background: grey;
  text-align: center;
  overflow: hidden;
  margin-bottom: 2%;
}

a {
  display: table-cell;
  width: 100em;
  height: 34px;
  vertical-align: middle;
}

Check it at codepen

创建这个:

enter image description here

关于css - 在 flexbox 布局中垂直居中链接文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23918099/

相关文章:

css - CSS 会影响 HTML 语义吗?

javascript - 当网站响应时,HTML/CSS 导航下拉菜单和子下拉菜单不显示

javascript - 如何使模态框响应?

css - 重新加载页面时 Gif 不工作。仅在窗口首次打开时有效

css3 z-index 问题,不工作?

javascript - 同一页面内的偏移链接

css - 从特定 anchor 标记中删除下划线

html - 父元素负边距和子元素似乎是合作的

html - 图片之间奇怪的下划线。这些是什么?

javascript - 页面加载时背景变灰