- font¶
- Демо¶
- Синтаксис¶
- Значения¶
- Спецификации¶
- Описание и примеры¶
- How to Apply Global Font to the Entire HTML Document
- Create HTML
- Add CSS
- Example of applying a global font to the entire HTML document:
- Example of applying a global font to the entire HTML document using the !important rule:
- Css html global font
- # Setting a global font family in React
- # Using a font from a local file in React.js
- # Using a global font from a CDN in React.js
font¶
Свойство font универсальное свойство, которое позволяет одновременно задать несколько характеристик шрифта и текста.
Демо¶
- font
- font-family
- font-feature-settings
- font-kerning
- font-language-override
- font-optical-sizing
- font-size
- font-size-adjust
- font-stretch
- font-style
- font-synthesis
- font-variant
- font-variant-alternates
- font-variant-caps
- font-variant-east-asian
- font-variant-ligatures
- font-variant-numeric
- font-variant-position
- font-variation-settings
- font-weight
- line-height
Синтаксис¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* size | family */ font: 2em 'Open Sans', sans-serif; /* style | size | family */ font: italic 2em 'Open Sans', sans-serif; /* style | variant | weight | size/line-height | family */ font: italic small-caps bolder 16px/3 cursive; /* style | variant | weight | stretch | size/line-height | family */ font: italic small-caps bolder condensed 16px/3 cursive; /* The font used in system dialogs */ font: message-box; font: icon; /* Global values */ font: inherit; font: initial; font: unset;
Значения¶
В качестве обязательных значений свойства font указывается размер шрифта и его семейство. Остальные значения являются опциональными и задаются при желании. Для подробного ознакомления смотрите информацию о каждом свойстве отдельно.
Допускается в качестве значения использовать ключевые слова, определяющие шрифт различных элементов операционной системы пользователя.
caption Шрифт для текста элементов форм вроде кнопок. icon Шрифт для текста под иконками. menu Шрифт применяемый в меню. message-box Шрифт для диалоговых окон. small-caption Шрифт для подписей к небольшим элементам управления. status-bar Шрифт для строки состояния окон.
Значение по-умолчанию: зависит от использования
Применяется ко всем элементам
Спецификации¶
Описание и примеры¶
p font: 12pt/10pt sans-serif; >
Из типографики пошла запись указывать через слэш размер шрифта и высоту строки. Поэтому 12pt в данном случае означает размер основного текста в пунктах, а 10pt — высоту строки. В качестве семейства указывается рубленый шрифт ( sans-serif ).
p font: bold italic 110% serif; >
Значение bold устанавливает жирное начертание текста, а italic — курсивное. В данном случае их порядок не важен, поэтому bold и italic можно поменять местами. Размер текста задаётся в процентах, а в качестве гарнитуры используется шрифт с засечками ( serif ).
p font: normal small-caps 12px/14px fantasy; >
Значение small-caps принадлежит свойству font-variant и устанавливает текст в виде капители (заглавные буквы уменьшенного размера). Значение normal применяется сразу к двум свойствам: font-style и font-weight .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
html> head> meta charset="utf-8" /> title>fonttitle> style> .layer1 font: 12pt sans-serif; > h1 font: 2em serif; > style> head> body> div class="layer1"> h1>Экзистенциальный либерализмh1> p> Карл Маркс исходил из того, что типология средств массовой коммуникации неизбежна. p> div> body> html>
How to Apply Global Font to the Entire HTML Document
Sometimes you may face the situation when there is a need to apply the same font-family and font-size to the entire HTML document.
In this snippet, we’re going to apply a global font format to the whole HTML page.
Here, you can find two examples, one of them with the CSS !important rule applied.
Create HTML
h1>Heading h1> p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p>
Add CSS
- Add the CSS * (asterisk) selector to select all the elements of the document.
- Set the font-size, font-family, line-height, and color properties.
html * < font-size: 16px; line-height: 1.625; color: #2020131; font-family: Nunito, sans-serif; >
Example of applying a global font to the entire HTML document:
html> html> head> title>Title of the document title> style> html * < font-size: 16px; line-height: 1.625; color: #2020131; font-family: Nunito, sans-serif; > style> head> body> h1>Heading h1> p> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p> body> html>
If you need to ensure that nothing can override what is set in that style, use the CSS !important rule. It is used to ignore the inner formatting of text, i.e., other styles cannot overwrite the styles with !important.
Next, we’ll demonstrate an example where we use the !important rule for all our CSS properties.
Example of applying a global font to the entire HTML document using the !important rule:
html> html> head> title>Title of the document title> style> html * < font-size: 16px !important; line-height: 1.625 !important; color: #2020131 !important; font-family: Nunito, sans-serif !important; > style> head> body> h1>Heading h1> p> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p> body> html>
Css html global font
Last updated: Jan 17, 2023
Reading time · 3 min
# Setting a global font family in React
To set a global font family in React, set the font-family style on the html element in your index.css file and import the file in your index.js file.
Global CSS should be imported in index.js to make sure it’s loaded on all pages of your React app.
Here is an example of setting the font-family CSS property in our index.css file.
Copied!body, html font-family: Roboto, Helvetica, sans-serif; /* 👇️ or use Operating system default fonts 👇️ */ /* font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; */ >
And here is how we would import the index.css file in our index.js file.
Copied!// 👇️ import css import './index.css'; import createRoot> from 'react-dom/client'; import App from './App'; const rootElement = document.getElementById('root'); const root = createRoot(rootElement); root.render( App /> );
The example above assumes that your index.css file is located in the same directory as your index.js file.
When importing global CSS files in React, it’s a best practice to import the CSS file into your index.js file.
The index.js file is the entry point of your React application, so it’s always going to run.
On the other hand, if you import a CSS file into a component, the CSS styles might get removed once your component unmounts.
I can add an App.js file with a component to verify the global font is applied.
Copied!const App = () => return ( div> div>bobbyhadz.comdiv> div> ); >; export default App;
# Using a font from a local file in React.js
If you have downloaded a font and need to load the font from a local file, create a fonts directly in your src folder and move your fonts there.
Now you can import them in your index.css file.
The following example assumes that you have downloaded the Poppins font into your src/fonts directory.
Copied!body, html font-family: 'Poppins', sans-serif; > @font-face font-family: 'Poppins'; src: local('Poppins'), url(./fonts/Poppins-Regular.ttf) format('truetype'); > @font-face font-family: 'Poppins'; font-weight: 900; src: local('Poppins'), url(./fonts/Poppins-Bold.ttf) format('truetype'); > @font-face font-family: 'Poppins'; font-weight: 900; src: local('Poppins'), url(./fonts/Poppins-Black.ttf) format('truetype'); >
For .ttf format we pass truetype to the format() function.
For .woff format, we pass woff to the format() function.
For .otf format, we pass opentype to the format() function.
You can download a font by picking one from google fonts and clicking on the Download all button.
# Using a global font from a CDN in React.js
If you are setting a global font family based on external styles, e.g. from google fonts CDN, make sure to load the style in your public/index.html file.
For example, with google fonts, you can click on the chosen font and then click «Select this style» and you will get a link you can add to the head tag of your index.html file.
Copied!DOCTYPE html> html lang="en"> head> link rel="preconnect" href="https://fonts.googleapis.com" /> link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> link href="https://fonts.googleapis.com/css2?family=Square+Peg&display=swap" rel="stylesheet" /> title>React Apptitle> head> body> noscript>You need to enable JavaScript to run this app.noscript> div id="root">div> body> html>
After you copy the link tag in the head section of your index.html file in the public/ directory, you still have to set the font-family property in your index.css file.
Copied!body, html font-family: 'Square Peg', cursive; >
The value of the font-family property will depend on the specific font you selected. You should be able to find it right below where you got the link tag from.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.