Font family change in html

Where to set font-family: body or html element?

If you are using rem units, make sure to set the base font size on the html element. rem units are based off the font size of the root element, which is the html element.

10 Answers 10

The short answer is, you can use either. Since every displayed element is a descendant of the body element, and the body element itself is the child of the html element, all elements that inherit the font-family property will happily adopt it from either. (If a particular element doesn’t inherit it, you can always override its font-family property with a value of inherit .)

But what is best practice, and why? That’s a bit harder to answer, but I’ll have a go. Let’s start with semantics…

The html element represents the whole document (including non-visible metadata), while the body element represents the content of the document. Since font-family is a property of styled content, it would seem logical to apply it to body . That’s one point for body .

Next question: Where do the browsers define text formatting properties like font-family ? I looked at the user agent stylesheets for Safari (WebKit), Mozilla Firefox and Chrome, and also used the Web Inspector on a page with no overriding CSS, but I couldn’t find a global font-family declaration anywhere. But here’s something interesting… In Safari, the global text color property is defined on the html element. So, if that’s anything to go by, it suggests WebKit browsers do define global font properties on the html element.

There are CSS resets that also tackle it here, like Bootstrap’s _reboot.scss file:

// 2. Change the default font family in all browsers. html < font-family: sans-serif; // 2 … >

Still, we can override this on the body element, and that is just what Bootstrap does a few lines later:

The CSS specs (as far as I know) don’t dictate where font-family is declared (it applies to ‘all elements’), but it does give us some hints. The first code example in the W3C document CSS Fonts Module Level 3 is this:

The first declaration on the BODY element sets the font family to «Gill Sans». If that font is not available, the user agent (often referred to as a «browser») will use the sans-serif font family which is one of five generic font families which all users agents know. Child elements of BODY will inherit the value of the font-family property.

Источник

Читайте также:  Php functions with mysqli

How to Change Font with HTML

Kolade Chris

Kolade Chris

How to Change Font with HTML

Back in the days of HTML4, there was a tag you could use to change the font size, font family, and the color of a text.

But with HTML5, the tag has been deprecated. So if you want to change anything related to the font, you have to do it with CSS.

In this article, I will show you how to change the font size, font weight, font style, and font family of text using CSS.

How to Change the Font Size of Text

The font size of text represents how big that text is.

To change the font size of some text, you need to use the font-size property and then specify the value in pixels ( px ), rem , or em .

You can do it using inline CSS like this:

You can also do it in embedded or internal CSS:

And finally you can do it in external CSS:

To get rid of the default white background and center the text both horizontally and vertically, I wrote this CSS:

ss1-2

In the browser, it looks as shown below:

How to Change the Font-weight of Text

Font-weight is the property that helps set how bold or light specific text will be.

You can use font-weight to change the lightness or boldness of text, then give it a value such as normal , lighter , bold , or bolder . You can also use values like 100, 200, 500, and so on.

Just like font size, you can change the font-weight in inline, embedded, or external CSS.

 

freeCodeCamp Lighter

freeCodeCamp Normal

freeCodeCamp Bold

freeCodeCamp Bolder

 .lighter < font-weight: lighter; >.normal < font-weight: normal; >.bold < font-weight: bold; >.bolder 
.lighter < font-weight: lighter; >.normal < font-weight: normal; >.bold < font-weight: bold; >.bolder

ss2-2

How to Change the Font Style of Text

Font style is the typeface variation of the text. This typeface variation could be normal , bold , or italic .

To change the font style, you need the font-style property with a value of normal , oblique , or italic .

Normal is the default font style, so you don’t need to specify it unless you have to override it.

As usual, you can change the font style in inline, internal, or external CSS.

 

freeCodeCamp Normal

freeCodeCamp Oblique

freeCodeCamp Italic

ss3-2

Here’s the output in the browser:

How to Change the Font Family of Text

A font family represents a collection of fonts that share the same design and typography.

To change the font family of some text, you need to use the CSS font-family property.

You can then choose to do it with inline CSS, internal CSS, or external CSS.

The code snippet below shows how to change the font-family in inline CSS:

 

freeCodeCamp

You can change the font-family in embedded or internal CSS this way: ```css h1

In an external CSS file you can change the font family like this:

Make sure the external CSS is linked to the HTML file, otherwise it won’t work.

ss4-1

The Verdana font family looks like this inside the Google Chrome browser:

You might have noticed that there are other font families in the value – Geneva, Tahoma, and sans-serif.

Those are fallbacks the browser can use in case Verdana is not available on the user’s device.

If you don’t like the fonts built into your device, you can get other ones from Google Fonts.

ss5-1

Search for your favorite font and copy the link to it, then paste the link in the section of your HTML so you can have access to it in your HTML stylesheet

In my case, I used the Roboto font like this:

ss6-1

And this is how it looks in the browser:

Conclusion

This article walked you through how to change the font size, font weight, font style, and font family of text in inline, internal, or external CSS.

You might be wondering which is best to use between inline, internal, or external CSS.

If you’re working on a small project, you can use internal or embedded CSS, but if you’re working on a big project or in a team, you should not use internal CSS.

This is because it is a best practice to keep your CSS away from your HTML.

Inline CSS is a no-no in most situations because it might affect the readability of your HTML.

It’s also been suggested that inline CSS can negatively affect the SEO of a website.

Источник

Как установить стиль шрифта. CSS-свойство font

Свойство font используется для оформления текста на сайте. Оно позволяет задавать различные атрибуты шрифта: размер, начертание, жирность, стиль и цвет.

Свойство в общем виде записывается так:

font-family — устанавливает семейство шрифтов.

font-style — задаёт стиль шрифта.

font-variant — определяет вариант шрифта.

font-weight — задаёт жирность шрифта.

font-size — указывает размер шрифта.

line-height — задаёт высоту строки.

Значения и примеры использования

Font-family

В значении свойства font-family указывается список названий шрифтов, перечисленных через запятую. В начале списка располагают самый желаемый шрифт, затем альтернативный, а в самом конце списка — общий тип шрифта. Браузер проходит по списку слева направо и использует первый найденный в системе или на сайте шрифт.

Font-style

Можно выбрать один из стилей оформления текста: обычный шрифт normal , курсив italic , наклонный oblique .

Font-variant

У свойства font-variant несколько значений:

small-caps — все строчные символы отображаются как заглавные уменьшенного размера.

Font-weight

Насыщенность шрифта можно определить числовым значением от 100 до 900 или ключевым словом, например, обычный шрифт normal , полужирный bold .

Возможные значения font-weight :

  • 100: Thin;
  • 200: Extra Light (Ultra Light);
  • 300: Light;
  • 400: Normal;
  • 500: Medium;
  • 600: Semi Bold (Demi Bold);
  • 700: Bold;
  • 800: Extra Bold (Ultra Bold);
  • 900: Black (Heavy).

Но в большинстве системных шрифтов есть только два варианта толщины: обычный normal (400) и полужирный bold (700).

Font-size

Размер шрифта font-size измеряется в пикселях ( px ), процентах, относительных ( em , rem ) или абсолютных единицах ( pt , cm , mm ).

Абсолютную величину шрифта можно задавать не только в пикселях, пунктах или других величинах, но и особыми ключевыми словами: xx-small , x-small , small , medium , large , x-large и xx-large . Подробно об этих ключевых словах можно узнать в спецификации.

Line-height

Свойство line-height устанавливает высоту строки, указывая множитель относительно размера шрифта. По умолчанию line-height имеет значение normal . Оно указывает браузеру, что межстрочный интервал нужно подобрать автоматически, исходя из размера шрифта.

Наследование

Свойство font наследуется от родительского элемента на его дочерние элементы.

Нюансы

✅ Если заданы различные атрибуты шрифта в разных правилах для одного элемента, последнее применённое свойство переопределит предыдущие.

Для второго абзаца заданы сначала общие параметры, а затем переопределены в селекторе по классу

✅ Если указанное семейство шрифтов не доступно на устройстве пользователя, браузер будет искать и использовать следующий указанный шрифт из списка или использовать шрифт по умолчанию.

Шрифт PT Sans Regular недоступен, поэтому заголовок оформлен шрифтом Arial

⭐ Свойство font поддерживается современными браузерами. Актуальная информация — на caniuse.com.

Чем заменить свойство font

Если нужно управлять отдельными атрибутами шрифта, например, размером, начертанием, жирностью, можно использовать соответствующие отдельные свойства — font-size , font-style и font-weight .

Материалы по теме

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

Источник

Оцените статью