css 实用技巧 —— 文字和图标垂直居中对齐(四种方法)

方法一: 使用 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生成一个空格字符实现

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朝阳39

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值