Applying a single font to an entire website with CSS
I want to use a single font named «Algerian» across my whole website. So, I need to change all HTML tags and I don’t want to write different code for different tags like:
You may want to choose the answer from Jukka K. Korpela. It’s earlier than the current picked answer, for about one month, and has almost same content, anyway.
I suggest you never use answer of (Jan Hančič) because it applies your font to all html tags even the tag you don’t like to change. for example: if you make an img tag inside a td tag and made it text-align:center and vertical-align:middle. using this way your img tag will never be center of the TD. the best way: check your document and just apply the font format to the tags that have texts in them
10 Answers 10
Put the font-family declaration into a body selector:
All the elements on your page will inherit this font-family then (unless, of course you override it later).
An element inherits font-family from its parent only when no style sheet sets the font family for the element. Browser style sheets typically set font family at least for input , textarea , code , tt , and pre elements.
Doesn’t that apply the font family to every single element? This seems like it would apply it to unnecessary elements (like ) and be inefficient. I could definitely be wrong, but I’ve read to use caution with applying a style to everything.
Since noboy has mentioned this, the universal selector is know to be slow. more on that here: clairecodes.com/blog/…
The universal selector * refers to all elements, this css will do it for you:
But unfortunately if you are using FontAwesome icons, or any Icons that require their own font family, this will simply destroy the icons and they will not show the required view.
To avoid this you can use the :not selector, a sample of fontawesome icon is , so simply you can use:
this will apply this family to all elements in the document except the elements with the tag name , you can also do it for classes:
this will apply this family to all elements in the document except the elements with the class «fa» which refers to fontawesome default class, you can also target more than one class like this:
*:not(i):not(.fa):not(.YourClassName)
This answer gives a much needed detail as per the current use of styling in webpages due to the use of icons from bootstrap (glyphicons) and font awesome
please note than: (not selector) is CSS3 which is not compatible with all browsers. IE 9+ we must wait at least 10 years for all people around the world to leave IE -9 families forever 😀 :'(
The universal selector * refers to any element.
Ensure that mobile devices won’t change the font with their default font by using important along with the universal selector * :
Because under normal circumstances, you don’t and should not use !important period. You should be targeting CSS specificity whenever you try to style something. Blindly forcing the styling using !important is just bad practice and will cause issues further down the line.
As a different font is likely to be already defined by the browser for form elements, here are 2 ways to use this font everywhere:
There’ll still have a monospace font on elements like pre/code, kbd, etc but, in case you use these elements, you’d better use a monospace font there.
Important note: if very few people has this font installed on their OS, then the second font in the list will be used. Here you defined no second font so the default serif font will be used, and it’ll be Times, Times New Roman except maybe on Linux.
Two options there: use @font-face if your font is free of use as a downloadable font or add fallback(s): a second, a third, etc and finally a default family (sans-serif, cursive (*), monospace or serif). The first of the list that exists on the OS of the user will be used.
(*) default cursive on Windows is Comic Sans. Except if you want to troll Windows users, don’t do that 🙂 This font is terrible except for your children birthdays where it’s welcome.
font
Универсальное свойство, которое позволяет одновременно задать несколько характеристик шрифта и текста.
Синтаксис
font: [font-style||font-variant||font-weight] font-size [/line-height] font-family | inherit
Значения
В качестве обязательных значений свойства font указывается размер шрифта и его семейство. Остальные значения являются опциональными и задаются при желании. Для подробного ознакомления смотрите информацию о каждом свойстве отдельно.
inherit Наследует значение родителя.
Допускается в качестве значения использовать ключевые слова, определяющие шрифт различных элементов операционной системы пользователя.
caption Шрифт для текста элементов форм вроде кнопок. icon Шрифт для текста под иконками. menu Шрифт применяемый в меню. message-box Шрифт для диалоговых окон. small-caption Шрифт для подписей к небольшим элементам управления. status-bar Шрифт для строки состояния окон.
Примеры использования
Из типографики пошла запись указывать через слэш размер шрифта и межстрочное расстояние (интерлиньяж). Поэтому 12pt в данном случае означает размер основного текста в пунктах, а 10pt — интерлиньяж. В качестве семейства указывается рубленый шрифт ( sans-serif ).
Значение bold устанавливает жирное начертание текста, а italic — курсивное. В данном случае их порядок не важен, поэтому bold и italic можно поменять местами. Размер текста задается в процентах, а в качестве гарнитуры используется шрифт с засечками ( serif ).
Значение small-caps принадлежит свойству font-variant и устанавливает текст в виде капители (заглавные буквы уменьшенного размера). Значение normal применяется сразу к двум свойствам: font-style и font-weight .
HTML5 CSS2.1 IE Cr Op Sa Fx
.layer1 < font: 12pt sans-serif; >h1 Duis te feugifacilisi Duis autem dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit au gue duis dolore te feugat nulla facilisi.
Результат данного примера показан на рис. 1.
Рис. 1. Применение свойства font
Объектная модель
[window.]document.getElementById(» elementID «).style.fontБраузеры
Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .
CSS Fonts
Choosing the right font for your website is important!
Font Selection is Important
Choosing the right font has a huge impact on how the readers experience a website.
The right font can create a strong identity for your brand.
Using a font that is easy to read is important. The font adds value to your text. It is also important to choose the correct color and text size for the font.
Generic Font Families
In CSS there are five generic font families:
- Serif fonts have a small stroke at the edges of each letter. They create a sense of formality and elegance.
- Sans-serif fonts have clean lines (no small strokes attached). They create a modern and minimalistic look.
- Monospace fonts — here all the letters have the same fixed width. They create a mechanical look.
- Cursive fonts imitate human handwriting.
- Fantasy fonts are decorative/playful fonts.
All the different font names belong to one of the generic font families.
Difference Between Serif and Sans-serif Fonts
Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts.
Some Font Examples
Generic Font Family | Examples of Font Names |
---|---|
Serif | Times New Roman Georgia Garamond |
Sans-serif | Arial Verdana Helvetica |
Monospace | Courier New Lucida Console Monaco |
Cursive | Brush Script MT Lucida Handwriting |
Fantasy | Copperplate Papyrus |
The CSS font-family Property
In CSS, we use the font-family property to specify the font of a text.
Note: If the font name is more than one word, it must be in quotation marks, like: «Times New Roman».
Tip: The font-family property should hold several font names as a «fallback» system, to ensure maximum compatibility between browsers/operating systems. Start with the font you want, and end with a generic family (to let the browser pick a similar font in the generic family, if no other fonts are available). The font names should be separated with comma. Read more about fallback fonts in the next chapter.
Example
Specify some different fonts for three paragraphs:
.p1 <
font-family: «Times New Roman», Times, serif;
>
.p2 font-family: Arial, Helvetica, sans-serif;
>
.p3 font-family: «Lucida Console», «Courier New», monospace;
>