Font style italic что это
font-style
Internet Explorer | Chrome | Opera | Safari | Firefox | Android | iOS | |
6.0+ | 8.0+ | 1.0+ | 3.5+ | 1.0+ | 1.0+ | 1.0+ | 1.0+ |
Краткая информация
Значение по умолчанию | normal |
---|---|
Наследуется | Да |
Применяется | Ко всем элементам |
Ссылка на спецификацию | http://www.w3.org/TR/CSS21/fonts.html#propdef-font-style |
Версии CSS
Описание
Определяет начертание шрифта — обычное, курсивное или наклонное. Когда для текста установлено курсивное или наклонное начертание, браузер обращается к системе для поиска подходящего шрифта. Если заданный шрифт не найден, браузер использует специальный алгоритм для имитации нужного вида текста. Результат и качество при этом могут получиться неудовлетворительными, особенно при печати документа.
Синтаксис
font-style: normal | italic | oblique | inherit
Значения
HTML5 CSS2.1 IE Cr Op Sa Fx
Результат данного примера показан на рис. 1.
Рис. 1. Применение свойства font-style
Объектная модель
[window.]document.getElementById(» elementID «).style.fontStyle
Браузеры
Браузеры текст со значением oblique всегда отображают как курсив ( italic ).
Курсив CSS
В прошлой статье мы обсуждали спецификацию выделения текста жирным шрифтом. В текущей статье мы поговорим о том, как выделить текст курсивом HTML. Как и в случае с жирным текстом, курсивный текст можно сделать тремя способами:
Рассмотрим все три варианта, как можно сделать курсив в HTML, обсудим тонкости этого вопроса и какие способы удобнее и правильнее использовать в тех или иных ситуациях.
Курсивный текст: тег
Тег i (italic), по аналогии с тегом b для жирного текста, служит для физического выделения курсивного текста (это означает, что изменяется только начертание текста). Применение тега i:
Курсивный текст: тег
Хотя тег i остается валидным, с точки зрения оптимизации сайта лучше использовать тег em для выделения логически важных участков текста. Это означает, что поисковые роботы учитывают важность текста, помещенного между тегами :
Конструктор сайтов «Нубекс»
Но не стоит забывать, что текст, заключенный в теги i и em, хоть и отображаются практически одинаково (во всех современных браузерах), по своей сути являеются не совсем идентичными, как уже отмечалось выше. Поэтому использовать теги нужно по мере необходимости: тегом em HTML обрамлять важные участки текста, а визуальное курсивное оформление применять с помощью тега i или CSS-стилей. Рассмотрим теперь использование CSS-стилей для курсивного выделения текста.
Курсивный текст силами CSS
Для установления стилей отображения шрифтов в CSS применяется свойство font-style, которое может принимать значения: oblique (наклонный текст), italic (курсив) и normal (обычный шрифт).
Применение атрибута font-style на практике:
Но необходимо помнить, что некоторые браузеры текст со свойством font-style: oblique; могут интерпретировать не как наклонный текст, а как курсивный.
Жирный шрифт и курсив CSS
Жирный шрифт в CSS: свойство font-weight
Управлять жирностью шрифта в CSS можно с помощью значений свойства font-weight :
bold | Полужирный шрифт |
normal | Обычный шрифт |
bolder | Более жирный шрифт, чем у родителя |
lighter | Менее жирный шрифт, чем у родителя |
inherit | Наследует значение родителя |
Числовое значение от 100 до 900 | От очень тонкого до очень жирного шрифта |
Примечание: числовые значения от 100 до 900, означающие толщину шрифта, сработают только в том случае, если у шрифта, с которым вы работаете, предусмотрены эти варианты начертания. Данные значения используются в основном с веб-шрифтами, о которых мы говорили в первой подглаве.
Курсив в CSS: свойство font-style
Задать курсивное начертание шрифта можно при помощи значений свойства font-style :
italic | Курсивный шрифт |
oblique | Наклонный шрифт |
normal | Обычный шрифт |
inherit | Наследует значение родителя |
Значение normal устанавливает обычный стиль шрифта, а inherit позволяет наследовать стиль родителя.
Далее в книге: строчные и заглавные буквы с помощью свойства CSS text-transform.
Основы стилизирования текста и шрифта
В данной статье мы начнём путь к овладению стилизацией текста при помощи CSS. Мы подробно изучим основы стилизации текста и шрифта, такие как толщина, начертание, семейство, стенография, выравнивание текста и другие эффекты, а также рассмотрим междустрочный и межбуквенный интервалы.
Необходимые знания: | Базовые компьютерные знания, Основы HTML (раздел Введение в HTML), основы CSS (раздел Введение в CSS). |
---|---|
Задача: | Изучить основные свойства и техники, необходимые для стилизации текста на веб-страницах. |
Что участвует в стилизации текста в CSS?
Примечание: если приведённый выше абзац оставляет вас в замешательстве, то не имеет значения — вернитесь и просмотрите нашу статью о модели коробки, чтобы освежить теорию модели коробки, прежде чем продолжить.
Свойства CSS, используемые для стилизации текста, обычно делятся на две категории, которые мы рассмотрим отдельно в этой статье:
Примечание: имейте в виду, что текст внутри элемента все затронуты как одна единая сущность. Вы не можете выбирать и стилизовать подразделы текста, если вы не обернёте их в соответствующий элемент (например, или ), или использовать текстовый псевдоэлемент, такой как ::first-letter (выделяет первую букву текста элемента). first-line (выделяет первую строку текста элемента) или ::selection (выделяет текст, выделенный в данный момент курсором.)
Шрифты
Давайте сразу перейдём к рассмотрению свойств для стилизации шрифтов. В этом примере мы применим некоторые различные свойства CSS к одному и тому же образцу HTML, который выглядит следующим образом:
Color
The color (en-US) property sets the color of the foreground content of the selected elements (which is usually the text, but can also include a couple of other things, such as an underline or overline placed on text using the text-decoration (en-US) property).
color can accept any CSS color unit, for example:
This will cause the paragraphs to become red, rather than the standard browser default black, like so:
Font families
To set a different font on your text, you use the font-family property — this allows you to specify a font (or list of fonts) for the browser to apply to the selected elements. The browser will only apply a font if it is available on the machine the website is being accessed on; if not, it will just use a browser default font. A simple example looks like so:
This would make all paragraphs on a page adopt the arial font, which is found on any computer.
Web safe fonts
Speaking of font availability, there are only a certain number of fonts that are generally available across all systems and can therefore be used without much worry. These are the so-called web safe fonts.
Most of the time, as web developers we want to have more specific control over the fonts used to display our text content. The problem is to find a way to know which font is available on the computer used to see our web pages. There is no way to know this in every case, but the web safe fonts are known to be available on nearly all instances of the most used operating systems (Windows, macOS, the most common Linux distributions, Android, and iOS).
The list of actual web safe fonts will change as operating systems evolve, but it’s reasonable to consider the following fonts web safe, at least for now (many of them have been popularized thanks to the Microsoft Core fonts for the Web initiative in the late 90s and early 2000s):
Name | Generic type | Notes |
---|---|---|
Arial | sans-serif | It’s often considered best practice to also add Helvetica as a preferred alternative to Arial as, although their font faces are almost identical, Helvetica is considered to have a nicer shape, even if Arial is more broadly available. |
Courier New | monospace | Some OSes have an alternative (possibly older) version of the Courier New font called Courier. It’s considered best practice to use both with Courier New as the preferred alternative. |
Georgia | serif | |
Times New Roman | serif | Some OSes have an alternative (possibly older) version of the Times New Roman font called Times. It’s considered best practice to use both with Times New Roman as the preferred alternative. |
Trebuchet MS | sans-serif | You should be careful with using this font — it isn’t widely available on mobile OSes. |
Verdana | sans-serif |
Note: Among various resources, the cssfontstack.com website maintains a list of web safe fonts available on Windows and macOS operating systems, which can help you make your decision about what you consider safe for your usage.
Note: There is a way to download a custom font along with a webpage, to allow you to customize your font usage in any way you want: web fonts. This is a little bit more complex, and we will be discussing this in a separate article later on in the module.
Default fonts
The five names are defined as follows:
Term | Definition | Example |
---|---|---|
serif | Fonts that have serifs (the flourishes and other small details you see at the ends of the strokes in some typefaces) | My big red elephant |
sans-serif | Fonts that don’t have serifs. | My big red elephant |
monospace | Fonts where every character has the same width, typically used in code listings. | My big red elephant |
cursive | Fonts that are intended to emulate handwriting, with flowing, connected strokes. | My big red elephant |
fantasy | Fonts that are intended to be decorative. | My big red elephant |
Font stacks
Since you can’t guarantee the availability of the fonts you want to use on your webpages (even a web font could fail for some reason), you can supply a font stack so that the browser has multiple fonts it can choose from. This simply involves a font-family value consisting of multiple font names separated by commas, e.g.
In such a case, the browser starts at the beginning of the list and looks to see if that font is available on the machine. If it is, it applies that font to the selected elements. If not, it moves on to the next font, and so on.
It is a good idea to provide a suitable generic font name at the end of the stack so that if none of the listed fonts are available, the browser can at least provide something approximately suitable. To emphasise this point, paragraphs are given the browser’s default serif font if no other option is available — which is usually Times New Roman — this is no good for a sans-serif font!
A font-family example
Let’s add to our previous example, giving the paragraphs a sans-serif font:
This gives us the following result:
Font size
In our previous module’s CSS values and units article, we reviewed length and size units. Font size (set with the font-size property) can take values measured in most of these units (and others, such as percentages), however the most common units you’ll use to size text are:
A simple sizing example
Our new result is like so:
Font style, font weight, text transform, and text decoration
CSS provides four common properties to alter the visual weight/emphasis of text:
Let’s look at adding a couple of these properties to our example:
Our new result is like so:
Text drop shadows
You can apply drop shadows to your text using the text-shadow property. This takes up to four values, as shown in the example below:
The four properties are as follows:
Multiple shadows
You can apply multiple shadows to the same text by including multiple shadow values separated by commas, for example:
If we applied this to the
(en-US) element in our Tommy the cat example, we’d end up with this:
Note: You can see more interesting examples of text-shadow usage in the Sitepoint article Moonlighting with CSS text-shadow.
Text layout
With basic font properties out the way, let’s now have a look at properties we can use to affect text layout.
Text alignment
The text-align property is used to control how text is aligned within its containing content box. The available values are as follows, and work in pretty much the same way as they do in a regular word processor application:
If we applied text-align: center; to the
(en-US) in our example, we’d end up with this:
Line height
Applying this to the
elements in our example would give us this result:
Letter and word spacing
The letter-spacing and word-spacing properties allow you to set the spacing between letters and words in your text. You won’t use these very often, but might find a use for them to get a certain look, or to improve the legibility of a particularly dense font. They can take most length and size units.
So as an example, we could apply some word- and letter-spacing to the first line of each
element in our example:
Let’s add some to our example, like so:
Other properties worth looking at
The above properties give you an idea of how to start styling text on a webpage, but there are many more properties you could use. We just wanted to cover the most important ones here. Once you’ve become used to using the above, you should also explore the following:
Text layout styles:
Font shorthand
Among all those properties, only font-size and font-family are required when using the font shorthand property.
A forward slash has to be put in between the font-size and line-height properties.
A full example would look like this:
Active learning: Playing with styling text
In this active learning session, we don’t have any specific exercises for you to do: we’d just like you to have a good play with some font/text layout properties, and see what you can produce! You can either do this using offline HTML/CSS files, or enter your code into the live editable example below.
If you make a mistake, you can always reset it using the Reset button.
Test your skills!
You’ve reached the end of this article, and already did some skill testing in our Active Learning section, but can you remember the most important information going forward? You can find an assessment to verify that you’ve retained this information at the end of the module — see Typesetting a community school homepage.
This assessment tests all the knowledge discussed in this module, so you might want to read the other articles before moving on to it.
Summary
We hoped you enjoyed playing with text in this article! The next article will give you all you need to know about styling HTML lists.
Свойство font-style
Синтаксис
Описание
Свойство font-style устанавливает стиль шрифта.
Применяется: | ко всем элементам; |
---|---|
Наследование: | присутствует; |
Проценты: | не используются; |
Медиа : | визуальные. |
JavaScript
Поддержка браузерами
Спецификация
Значения
normal Устанавливает стандартный вариант шрифта.
italic Устанавливает курсивный вариант шрифта. В случаии отсутствия курсивного варианта веб-браузер выбирает наклонённый вариант.
oblique Устанавливает наклонённый вариант шрифта. В случаии отсутствия наклонённого варианта веб-браузер выбирает курсивный вариант. (Так же наклонённый вариант может быть сгенерирован путём искусственного наклонения глифов нормального варианта.)
inherit Указывает, что элемент должен унаследовать параметры родительского элемента.
Начальное значение: « normal ».
Пример использования
Стиль шрифта
Текст с использованием стандартного варианта шрифта.
>»italic» > Текст с использованием курсивного варианта шрифта.
>»oblique» > Текст с использованием наклонённого варианта шрифта.