html - 垂直和水平居中图标和文本

标签 html css

我有一个链接 block :

    <ul>
        <li><a href="#" class="icon26 icon1">Link 1</a></li>
        <li><a class="icon26 icon2">Link 2</a></li>
    </ul>

每个链接都有一个相应的图标。我想要实现的是两件事: 1) 将 LI 标签中的图像和文本居中 2) 屏蔽A标签,填充LI标签

这是我正在尝试做的事情:

enter image description here

我可以实现 1 或 2,但不能同时实现两者 - 有什么想法吗?

目前我正在为链接使用现有的 sprite 解决方案 - 这可能不是理想的,但如果找到解决方案,它可以更改。这是 CSS:

.icon26:before
{
    background:url(/assets/images/sprite26.png) no-repeat 0 0;
    content:"";
    display:block;
    float:left;
    height:2.6rem;
    width:2.6rem;
}

.icon1:before
{
    background-position:-32px -2px;
}

这是 UL 结构的剩余 CSS:

#nav ul
{
    width:100%;
}

#nav ul li
{
    float:left;
    width:33.33%;
}

#nav a
{
    display:block;
    line-height:4.6rem;
}

#nav a:before
{
    margin:1rem 0.5rem 1rem 0;
}

最佳答案

完全有可能。移除 float,并使用 display: inline-blockvertical-align: middle 的组合。

Here's the fiddle .

相关代码如下:

.icon26:before {
    background: url(/assets/images/sprite26.png) no-repeat 0 0;
    content: "";
    display: inline-block; /* <-- instead of float: left */
    vertical-align: middle; /* <-- add to vertically center inline blocks */
    height: 2.6rem;
    width: 2.6rem;
}

#nav ul li {
    float: left;
    width: 33.33%;
    text-align: center; /* <-- add this to horizontally center inline items */
}

关于html - 垂直和水平居中图标和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28041662/

相关文章:

css - div 布局(浮在其他元素上)

Python美汤: Target tag only within another

javascript - 刷新页面而不出现屏幕空白?

javascript - Bootstrap selectpicker 奇怪的行为

css - 使用 nth-child 减少最后 4 个容器

html - 带有自定义图像 CSS 代码的复选框不起作用

html - 不遵循 flex 百分比的 flex 布局

javascript - 按其父 div 缩放 svg

html - 如何在 Bootstrap 4 中垂直对齐?

html - 具有未定义列数的网格布局