如何在css文件中使用本地ttf/woff/woff2字体?

文章介绍了如何在CSS文件中引用并使用本地的ttf、woff和woff2字体文件。首先下载字体,然后通过`@font-face`规则定义字体家族和路径,接着在CSS样式中应用这些自定义字体,最后在HTML或JS中创建元素并应用相应的CSS类来展示不同字体效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何在css文件中使用本地ttf/woff/woff2字体?

1、首先下载ttf、woff、woff2字体文件

免费的字体文件可以上阿里矢量图库进行下载,不过数量很少。
在这里插入图片描述

2、在css文件中配置相应代码

@font-face { 
  font-family: 'myFont1'; 
  src: url('./myfont1.ttf') format('truetype');
  font-weight: 600;
  font-style: normal;
}

@font-face { 
  font-family: 'myFont2'; 
  src: url('./myfont2.woff') format('woff');
  font-weight: 600;
  font-style: normal;
}

@font-face { 
  font-family: 'myFont3'; 
  src: url('./myfont3.woff2') format('woff2');
  font-weight: 600;
  font-style: normal;
}

.hello1 {
  color: red;
  font-family: 'myFont1';
}
.hello2 {
  color: blue;
  font-family: 'myFont2';
}
.hello3 {
  color: pink;
  font-family: 'myFont3';
}

3、在js或html文件中使用css中的样式

import _ from 'lodash';
import './style.css';
 
function component() {
  const element1 = document.createElement('div');
  const element2 = document.createElement('div');
  const element3 = document.createElement('div');

  // Lodash, now imported by this script
  element1.innerHTML = _.join(['Hello', 'World'], ' ');
  element1.classList.add('hello1');
  element2.innerHTML = "Hello World";
  element2.classList.add('hello2');
  element3.innerHTML = "Hello World";
  element3.classList.add('hello3');

  element1.appendChild(element2);
  element1.appendChild(element3);

  return element1;
}

document.body.appendChild(component());

4、成果

3种不一样的字体
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值