🎨 CSS 文字样式:实现字体引入、斜体与渐变文字效果(适用于 Vue 项目)
在前端开发中,定制字体样式可以显著提升网页的视觉表现力。本文将结合 Vue 项目,介绍以下三种实用的文字样式技巧:
- 引入自定义字体(以
.ttf
为例) - 设置文字为斜体
- 实现文字颜色的渐变效果
1、 引入 .ttf
字体文件(以 Vue 2 为例)
📁 步骤 1:放置字体文件
将字体文件(如 MyFont.ttf
)放入 src/assets/fonts/
目录:
src/
└── assets/
└── fonts/
└── MyFont.ttf
步骤 2:创建字体样式文件
src/assets/fonts/fonts.css
@font-face {
font-family: 'MyFont';
src: url('./MyFont.ttf') format('truetype');
font-weight: normal;
font-style: normal;
font-display: swap;
}
步骤 3:在 main.js 中引入字体样式
import Vue from 'vue'
import App from './App.vue'
import './assets/fonts/fonts.css' // 引入字体文件
new Vue({
render: h => h(App),
}).$mount('#app')
步骤 4:使用字体
<template>
<div class="custom-text">使用自定义字体</div>
</template>
<style scoped>
.custom-text {
font-family: 'MyFont', sans-serif;
}
</style>
ℹ️ 关于 sans-serif:
在 font-family: ‘MyFont’, sans-serif; 中,sans-serif 是备用字体。如果 ‘MyFont’ 无法加载,则使用系统默认的无衬线字体,如 Arial 或 Helvetica。
2、 实现斜体文字
只需使用 font-style: italic:
<template>
<p class="italic-text">这是斜体文字</p>
</template>
<style scoped>
.italic-text {
font-style: italic;
}
</style>
属性值 | 含义 |
---|---|
normal | 正常字体(默认) |
italic | 使用字体本身的斜体样式(推荐) |
oblique | 模拟倾斜效果(非真实斜体) |
⚠️ 注意:中文字体如微软雅黑、苹方等可能没有真正的斜体,浏览器将模拟倾斜显示。
3、 实现字体颜色渐变(如上线渐变)
使用 linear-gradient 和 background-clip 技巧:
<template>
<div class="gradient-text">渐变字体效果</div>
</template>
<style scoped>
.gradient-text {
font-size: 48px;
font-weight: bold;
background: linear-gradient(to bottom, #ff6a00, #ffcc00);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
</style>
✅ 常见渐变方向:
渐变方向 | 示例代码 |
---|---|
上 → 下(默认) | linear-gradient(to bottom, #a, #b) |
下 → 上 | linear-gradient(to top, #a, #b) |
左 → 右 | linear-gradient(to right, #a, #b) |
多色渐变 | linear-gradient(to bottom, red, orange, yellow) |
✅ 总结:
功能 | CSS 技巧 |
---|---|
字体引入 | @font-face + 本地字体文件 .ttf |
文字斜体 | font-style: italic |
渐变字体颜色 | linear-gradient + background-clip: text |