在CSS中使用同一款Google字体的不同字重

5

我正在查看一个名为Roboto的Google字体

https://fonts.google.com/specimen/Roboto?selection.family=Roboto

它有不同的风格,比如轻体、常规体、中等体等。

该网站上说要导入可以这样做:

@import url('https://fonts.googleapis.com/css?family=Roboto');

然后在你的样式表中可以这样做:

font-family: 'Roboto', sans-serif;

好的,但我需要它们的混合。例如,轻和常规,而不仅仅是一个。

所以我可以这样做

@import url('https://fonts.googleapis.com/css?family=Roboto:300,400,500');

这条代码可以选择所有元素。

但是在样式表中,你仍然可以这样做:

font-family: 'Roboto', sans-serif

如果你这样做,它就只会遵循第一个。我需要一个样式是300,一个是400,一个是500。那么我该如何在CSS中指定哪个样式?
我尝试过这样做:
font-family: 'Roboto:300', sans-serif

并且。
font-family: 'Roboto 300', sans-serif

我尝试使用多种字体,包括font-family: 'Roboto-300', sans-serif,但都失败了。有人能帮忙吗?

2个回答

5

那么你的意思是我只需要“常规”的吗? - Chillin'
1
不,您必须导入所有想要使用的字体类型(普通、斜体、粗体、斜粗体等),然后通过使用“font-weight”属性在CSS中指定要使用哪种字体。请注意,“font-weight”可以设置文本的粗细程度,“font-style”可以将其设置为斜体或正常。 - Mattia Nocerino
1
啊,我明白了。谢谢。 - Chillin'
由于某种原因,似乎只有两种状态。正常和加粗。900的效果与加粗相同。但是300和400之间似乎没有区别。有什么想法吗? - Chillin'

0
我建议的是创建一个类来定义要使用的字体,即在导入Google字体后,在您的CSS中添加:
@import url('https://fonts.googleapis.com/css?family=Roboto:300,400,600');

.robotoriser{
font-family: 'Roboto', sans-serif;
font-weight: Normal; /*  This is just so when ever you call use this class, it uses the normal font weight by default */
}

.rbt-300{ /* you can also name this rbt-light or whatever you like*/
font-weight:300;
}

.rbt-400{
font-weight:400;
}

.rbt-600{
font-weight:600;
}

......等等。

然后在HTML中像这样使用

<p class="robotoriser rbt-300" >This is light text</p>

<p class="robotoriser rbt-400" >This is medium text</p>

<p class="robotoriser rbt-600" >This is heavy text</p>

这里有一个可工作演示的 fiddle 链接

请注意你也可以在任何你拥有的类中使用它,例如:

.some_element{
font-family: 'Roboto', sans-serif;
font-weight: 300; /* Or any of the font weight values you included via the Google font url  */
}

<p class="some_element"> Dragons are goats that can fly :D </p>

请检查以下内容,确保: - Ojanti
1
@user6950100 ,font-weight:300和 font-weight:300在上面我回答中的fiddle中并不相同。 请检查以下内容:
  • 检查你是否在Google字体URL中添加了所有的字重,并确保其有效。
  • 检查你的代码,找出是否有其他样式规则覆盖了你想要设置样式的类或元素的字重。
如果有链接我们可以查看,那就太好了。
- Ojanti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接