方法一: 使用 ex【推荐】

<template>
    <div style="padding: 20px;font-size: 30px">
      无论字体多大,ex都能实现文字和图标对齐<i class="icon-arrow"></i>
    </div>
</template>
<style scoped>
    .icon-arrow {
        display: inline-block;
        width: 20px;
        height: 1ex;
        background: url(https://demo.cssworld.cn/images/5/arrow.png) no-repeat center;
    }
</style>

方法二:使用 vertical-align的具体数值 

缺点:字体大小改变需同步调整 vertical-align的值

<template>
    <div style="padding: 20px;">
        使用 vertical-align 实现文字和图标垂直居中对齐<i class="icon-arrow"></i>
    </div>
</template>
<style scoped>
    .icon-arrow {
        vertical-align: -5px;
        display: inline-block;
        width: 20px;
        height: 20px;
        background: url(https://demo.cssworld.cn/images/5/arrow.png) no-repeat center;
    }
</style>

方法二:使用 vertical-align的百分比值

优点:无论字体多大都居中对齐

缺点:若 line-height 改变,vertical-align也许同步调整百分比值

原理: vertical-align: 25% 使文字中心线和图标的下边缘对齐,在通过相对定位的top,将图标向下偏移图标高度的一半

<template>
    <p>文字<i class="icon-arrow"/></p>
</template>
<style scoped>
    .icon-arrow {
        background: url(https://demo.cssworld.cn/images/5/arrow.png) no-repeat center;
        width: 16px;
        height: 16px;
        display: inline-block;
        position: relative;
        top: 8px;
        vertical-align: 25%;
    }
</style>

方法四: 使用行高

<template>
    <div style="padding: 20px;">
        <p class="content">使用 line-height 实现文字和图标垂直居中对齐<i class="myIcon icon-arrow"></i></p>
    </div>
</template>
<style scoped>
    .content {
        line-height: 20px;
    }

    .myIcon {
        width: 20px;
        height: 20px;
        display: inline-block;
    }

    .myIcon:before {
        /*\3000 为空格字符,  */
        content: '\3000';
    }

    .icon-arrow {
        background: url(https://demo.cssworld.cn/images/5/arrow.png) no-repeat center;
    }
</style>

要点:

1. 文本的line-height = 图标的height

2. 图标内永远有字符,使用:before生成一个空格字符实现

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐