Стили текста — Основы верстки контента
Создание страницы это, в первую очередь, работа с текстом. Каким бы ни был красивым дизайн, но если информацию прочитать трудно или невозможно, то пользователь быстро уйдет со страницы. CSS дает широкие возможности для стилизации текста. В этом уроке рассмотрим основные стили, которые возможно применить к тексту. Описать их все в рамках одного урока невозможно и в этом нет необходимости. В процессе получения опыта вы будете узнавать о новых свойствах, но все они базируются на нескольких основных «китах»:
- Цвет текста;
- Расположение текста;
- Отступы от текста;
- Размер текста.
Цвет текста
Каждый текст на странице имеет свой цвет. Будь то заголовки или кричащий баннер, который рассказывает о скидке. Любой текст имеет цвет. В CSS используется свойство color , чтобы управлять им. С его помощью можно установить любой цвет для разных участков текста. В качестве значения свойство принимает цвет в разных моделях цветового пространства. Распространенной является модель RGB. Она указывает, сколько красного, зеленого и синего используется в цвете. На первых порах вы можете использовать онлайн-сервисы, которые укажут выбранный цвет в этой модели. Одним из таких сервисов является HTML Colors Codes .
Первое, что настраивают разработчики во время верстки макета — цвет основного текста страницы. Так как свойство color является наследуемым, то его можно устанавливать для тега или . С помощью каскадности этот цвет будет применяться ко всему тексту, если не указано иного значения. Выберем неглубокий черный цвет, который записывается в модели HEX как #333333 .
Интересно: в макетах редко встречается максимально черный цвет, который записывается как #000000 . Дело в том, что такой цвет не встречается в природе и человеческому глазу непривычен
body color: #333; >
Установка цвета текста — непростая задача. Помимо решения дизайнерской задачи и согласования текста с остальными цветовыми решениями, необходимо не забывать про доступность текста. Какой бы цвет ни был выбран, его прочтение должно быть комфортным для пользователя. Для этого текст должен быть контрастным относительно фона, на котором он лежит. Светло-серый текст на белом фоне будет трудно прочитать. Поэтому на белом фоне используют черный или близкий к черному цвет для основного текста.
Контраст в меньшей степени относится к заголовкам и небольшим выделениям внутри текста. Они выделяются на общем фоне по другим характеристикам: насыщенность, размер, границы, самостоятельный фон. Такой текст тоже должен обладать достаточным контрастом, при этом он может иметь значения ниже, чем основной текст.
Для проверки контраста текста можно использовать веб-инспектор Chrome DevTools. Выбрав любой цвет на панели Styles, можно увидеть коэффициент контраста текста, автоматически выведенный браузером. Он обозначен как Contrast ratio. Если контраст находится в рамках допустимого, то будет отмечен зеленой галочкой. В противном случае будет показан красный круг.
Наследование значений свойств
При использовании свойств бывает удобно не указать конкретное значение, а взять значение из родительского элемента. Например, у ссылки есть цвет по умолчанию. Во многих дизайнах цвет ссылки совпадает с основным цветом текста. Для этого можно отдельно задать цвет для ссылки и сделать его таким же, указав то же значение.
body color: #333; > a color: #333; >
Этот способ приводит к повторению одних и тех же значений, что плохо сказывается в больших проектах. Изменение цвета шрифта означает, что нужно не забыть изменить цвет ссылки.
Один из способов решения проблемы — значение inherit , с английского — наследовать. Указав color: inherit мы скажем браузеру установить цвет таким же, как у родительского элемента.
body color: #333; > a color: inherit; >
Значение inherit применяется для многих свойств, но, чаще всего, используется при работе с текстом и его оформлением. В качестве значения будет использован именно ближайший родитель. Это не обязательно будет — всё зависит от структуры вашей верстки и CSS.
Выравнивание текста
Выравнивание текста является важным способом выделения текста на странице. Нестандартное выравнивание позволяет пользователю быстрее заметить текст. В связке с размером текста и цветом, выравнивание заголовков является общепризнанной практикой на страницах.
Для выравнивания текста используется свойство text-align , которое принимает следующие значения:
- left — выравнивание текста по левому краю. Это значение устанавливается по умолчанию.
- center — выравнивание текста по центру.
- right — выравнивание текста по правому краю.
- justify — выравнивание текста по ширине. Данное значение выравнивает текст так, чтобы поместить слова строго от начала блока до его конца. При этом возможны изменения размеров пробелов между словами.
Важно: использование значения justify является плохой практикой. Данный прием используется в оформлении книг, где есть возможность отредактировать текст так, чтобы выравнивание по ширине не создавало больших пробелов между словами. В условиях веб-страницы такое почти невозможно.
Свойство text-align также является наследуемым. Если установить его для какого-либо блока, то весь текст внутри него будет выровнен в соответствии со значением свойства.
Насыщенность текста
Используя CSS можно гибко настраивать насыщенность шрифта. Насыщенность используется для выделения важного участка текста и придает ему «вес» относительно соседних элементов. Для управления насыщенностью в CSS используется правило font-weight . Оно принимает следующие значения:
- Значения от 100 до 900 с шагом 100
- lighter — сверхтонкое начертание. Делает текст менее насыщенным, чем текущее значение
- normal — значение по умолчанию. Соответствует числовому значению 400
- bold — жирное начертание текста. Соответствует числовому значению 700
- bolder — сверхжирное начертание. Делает текст насыщеннее, чем текущее значение
Для многих шрифтов доступны только значения normal и bold . Это связано с тем, сколько создатели шрифта включат различных начертаний.
Размер текста
Управлять размером текста можно с помощью свойства font-size . Текст с большим размером шрифта первым бросается в глаза, поэтому заголовки, помимо выравнивания по центру, имеют больший размер шрифта.
Сравните заголовки, которые создаются с помощью тегов и . Основное их визуальное отличие — размер текста. Помимо встроенных стилей, мы можем самостоятельно устанавливать размер шрифта. Для этого можно использовать единицы измерения пиксели px . В следующих уроках вы узнаете и о других единицах измерения и как с их помощью можно адаптировать контент.
.small-text font-size: 12px; > .normal-text font-size: 16px; > .big-text font-size: 30px; >
Открыть доступ
Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно
- 130 курсов, 2000+ часов теории
- 1000 практических заданий в браузере
- 360 000 студентов
Наши выпускники работают в компаниях:
Свойства текста
С помощью CSS можно определять стиль и вид текста. Аналогично тому, что используется тег , задающий свойства шрифта, но стили обладают большими возможностями и позволяют сократить код HTML.
Свойства шрифта
Изменение начертания шрифта и его размера происходит через свойства CSS, которые описаны в табл. 1.
Свойство | Значение | Описание | Пример |
---|---|---|---|
font-family | имя шрифта | Задает список шрифтов | P |
font-style | normal italic oblique |
Нормальный шрифт Курсив Наклонный шрифт |
P |
font-variant | normal small-caps |
Капитель (особые прописные буквы) | P |
font-weight | normal lighter bold bolder 100–900 |
Нормальная жирность Светлое начертание Полужирный Жирный 100 — светлый шрифт, 900 — самый жирный |
P |
font-size | normal pt px % |
нормальный размер пункты пикселы проценты |
font-size: normal font-size: 12pt font-size: 12px font-size: 120% |
В примере 1 показано использование параметров при работе со шрифтами.
Пример 1. Задание свойств шрифта с помощью CSS
Шрифт Заголовок
Обычный текст
Ниже приведен результат данного примера (рис. 1).
Рис. 1. Вид текста после применения стилей
В табл. 2 приведены некоторые стилевые параметры для работы с текстом и результат их применения.
Пример | Пример | Пример | Пример | Пример |
font-family: Verdana, sans-serif; font-size: 120%; font-weight: light | font-size: large; font-weight: bold | font-family: Arial, sans-serif; font-size: x-small; font-weight: bold | font-variant: small-caps | font-style: italic; font-weight: bold |
Свойства текста
Кроме изменения параметров шрифтов, можно управлять и свойствами всего текста. Значения свойств приведены в табл. 3.
Свойство | Значение | Описание | Пример |
---|---|---|---|
line-height | normal множитель значение % |
Интерлиньяж (межстрочный интервал) | line-height: normal line-height: 1.5 line-height: 12px line-height: 120% |
text-decoration | none underline overline line-through blink |
Убрать все оформление Подчеркивание Линия над текстом Перечеркивание Мигание текста |
text-decoration: none |
text-transform | none capitalize uppercase lowercase |
Убрать все эффекты Начинать С Прописных ВСЕ ПРОПИСНЫЕ все строчные |
text-transform: capitalize |
text-align | left right center justify |
Выравнивание текста | text-align: justify |
text-indent | значение % |
Отступ первой строки | text-indent: 15px; text-indent: 10% |
Ниже, в табл. 4 приведены некоторые параметры текста и результат их применения.
Пример: и это все о нем | Пример: текст по центру | Пример: Это не ссылка, а просто текст | Пример: отступ первой строки | Пример: полуторный межстрочный интервал |
text-transform: capitalize | text-align:center | text-decoration: underline | text-indent: 20px | line-height: 1.5 |
Основы стилизирования текста и шрифта
В данной статье мы начнём путь к овладению стилизацией текста при помощи CSS. Мы подробно изучим основы стилизации текста и шрифта, такие как толщина, начертание, семейство, стенография, выравнивание текста и другие эффекты, а также рассмотрим междустрочный и межбуквенный интервалы.
Необходимые знания: | Базовые компьютерные знания, Основы HTML (раздел Введение в HTML), основы CSS (раздел Введение в CSS). |
---|---|
Задача: | Изучить основные свойства и техники, необходимые для стилизации текста на веб-страницах. |
Что участвует в стилизации текста в CSS?
Как вы уже проверили в своей работе с HTML и CSS, текст внутри элемента выкладывается в поле содержимого элемента. Он начинается в левом верхнем углу области содержимого (или в правом верхнем углу, в случае содержимого языка RTL) и течёт к концу строки. Как только он достигает конца, он переходит к следующей строке и продолжает, затем к следующей строке, пока все содержимое не будет помещено в коробку. Текстовое содержимое эффективно ведёт себя как ряд встроенных элементов, размещённых на соседних строках и не создающих разрывы строк до тех пор, пока не будет достигнут конец строки, или если вы не принудите разрыв строки вручную с помощью элемента .
Примечание: если приведённый выше абзац оставляет вас в замешательстве, то не имеет значения — вернитесь и просмотрите нашу статью о модели коробки, чтобы освежить теорию модели коробки, прежде чем продолжить.
Свойства CSS, используемые для стилизации текста, обычно делятся на две категории, которые мы рассмотрим отдельно в этой статье:
- Font styles: Свойства, влияющие на шрифт, применяемый к тексту, влияющие на то, какой шрифт применяется, насколько он велик, является ли он полужирным, курсивным и т. д.
- Text layout styles: Свойства, влияющие на интервал и другие особенности компоновки текста, позволяющие манипулировать, например, пространством между строками и буквами, а также тем, как текст выравнивается в поле содержимого.
Примечание: имейте в виду, что текст внутри элемента все затронуты как одна единая сущность. Вы не можете выбирать и стилизовать подразделы текста, если вы не обернёте их в соответствующий элемент (например, или ), или использовать текстовый псевдоэлемент, такой как ::first-letter (выделяет первую букву текста элемента). first-line (выделяет первую строку текста элемента) или ::selection (выделяет текст, выделенный в данный момент курсором.)
Шрифты
Давайте сразу перейдём к рассмотрению свойств для стилизации шрифтов. В этом примере мы применим некоторые различные свойства CSS к одному и тому же образцу HTML, который выглядит следующим образом:
h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p>
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:
p color: red; >
This will cause the paragraphs to become red, rather than the standard browser default black, like so:
h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p>
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:
p font-family: arial; >
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 |
Примечание: 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.
Примечание: 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
CSS defines five generic names for fonts: serif , sans-serif , monospace , cursive and fantasy . Those are very generic and the exact font face used when using those generic names is up to each browser and can vary for each operating system they are running on. It represents a worst case scenario where the browser will try to do its best to provide at least a font that looks appropriate. serif , sans-serif and monospace are quite predictable and should provide something reasonable. On the other hand, cursive and fantasy are less predictable and we recommend using them very carefully, testing as you go.
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.
p font-family: "Trebuchet MS", Verdana, sans-serif; >
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!
Примечание: Font names that have more than one word — like Trebuchet MS — need to be surrounded by quotes, for example «Trebuchet MS» .
A font-family example
Let’s add to our previous example, giving the paragraphs a sans-serif font:
p color: red; font-family: Helvetica, Arial, sans-serif; >
This gives us the following result:
h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p>
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:
- px (pixels): The number of pixels high you want the text to be. This is an absolute unit — it results in the same final computed value for the font on the page in pretty much any situation.
- em s: 1 em is equal to the font size set on the parent element of the current element we are styling (more specifically, the width of a capital letter M contained inside the parent element.) This can become tricky to work out if you have a lot of nested elements with different font sizes set, but it is doable, as you’ll see below. Why bother? It is quite natural once you get used to it, and you can use em to size everything, not just text. You can have an entire website sized using em , which makes maintenance easy.
- rem s: These work just like em , except that 1 rem is equal to the font size set on the root element of the document (i.e. ), not the parent element. This makes doing the maths to work out your font sizes much easier, although if you want to support really old browsers, you might struggle — rem is not supported in Internet Explorer 8 and below.
The font-size of an element is inherited from that element’s parent element. This all starts with the root element of the entire document — — the font-size of which is set to 16 px as standard across browsers. Any paragraph (or another element that doesn’t have a different size set by the browser) inside the root element will have a final size of 16 px . Other elements may have different default sizes, for example an (en-US) element has a size of 2 em set by default, so it will have a final size of 32 px .
article> p>My paragraphp> article>
You would need to set its em value to 20/24, or 0.83333333 em . The maths can be complicated, so you need to be careful about how you style things. It is best to use rem where you can, to keep things simple, and avoid setting the font-size of container elements where possible.
A simple sizing example
When sizing your text, it is usually a good idea to set the base font-size of the document to 10 px , so that then the maths is a lot easier to work out — required (r)em values are then the pixel font size divided by 10, not 16. After doing that, you can easily size the different types of text in your document to what you want. It is a good idea to list all your font-size rulesets in a designated area in your stylesheet, so they are easy to find.
Our new result is like so:
h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p>
html font-size: 10px; > h1 font-size: 5rem; > p font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; >
Font style, font weight, text transform, and text decoration
CSS provides four common properties to alter the visual weight/emphasis of text:
- font-style : Used to turn italic text on and off. Possible values are as follows (you’ll rarely use this, unless you want to turn some italic styling off for some reason):
- normal : Sets the text to the normal font (turns existing italics off.)
- italic : Sets the text to use the italic version of the font if available; if not available, it will simulate italics with oblique instead.
- oblique : Sets the text to use a simulated version of an italic font, created by slanting the normal version.
- normal , bold : Normal and bold font weight
- lighter , bolder : Sets the current element’s boldness to be one step lighter or heavier than its parent element’s boldness.
- 100 – 900 : Numeric boldness values that provide finer grained control than the above keywords, if needed.
- none : Prevents any transformation.
- uppercase : Transforms all text to capitals.
- lowercase : Transforms all text to lower case.
- capitalize : Transforms all words to have the first letter capitalized.
- full-width : Transforms all glyphs to be written inside a fixed-width square, similar to a monospace font, allowing aligning of e.g. Latin characters along with Asian language glyphs (like Chinese, Japanese, Korean).
- none : Unsets any text decorations already present.
- underline : Underlines the text.
- overline : Gives the text an overline.
- line-through : Puts a strikethrough over the text .
Let’s look at adding a couple of these properties to our example:
Our new result is like so:
h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p>
html font-size: 10px; > h1 font-size: 5rem; text-transform: capitalize; > h1 + p font-weight: bold; > p font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; >
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:
text-shadow: 4px 4px 5px red;
The four properties are as follows:
- The horizontal offset of the shadow from the original text — this can take most available CSS length and size units, but you’ll most commonly use px ; positive values move the shadow right, and negative values left. This value has to be included.
- The vertical offset of the shadow from the original text; behaves basically just like the horizontal offset, except that it moves the shadow up/down, not left/right. This value has to be included.
- The blur radius — a higher value means the shadow is dispersed more widely. If this value is not included, it defaults to 0, which means no blur. This can take most available CSS length and size units.
- The base color of the shadow, which can take any CSS color unit. If not included, it defaults to black .
Multiple shadows
You can apply multiple shadows to the same text by including multiple shadow values separated by commas, for example:
text-shadow: 1px 1px 1px red, 2px 2px 1px red;
If we applied this to the (en-US) element in our Tommy the cat example, we’d end up with this:
h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p>
html font-size: 10px; > h1 font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; > h1 + p font-weight: bold; > p font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; >
Примечание: 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:
- left : Left-justifies the text.
- right : Right-justifies the text.
- center : Centers the text.
- justify : Makes the text spread out, varying the gaps in between the words so that all lines of text are the same width. You need to use this carefully — it can look terrible, especially when applied to a paragraph with lots of long words in it. If you are going to use this, you should also think about using something else along with it, such as hyphens , to break some of the longer words across lines.
If we applied text-align: center; to the (en-US) in our example, we’d end up with this:
h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p>
html font-size: 10px; > h1 font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; text-align: center; > h1 + p font-weight: bold; > p font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; >
Line height
The line-height property sets the height of each line of text — this can take most length and size units, but can also take a unitless value, which acts as a multiplier and is generally considered the best option — the font-size is multiplied to get the line-height . Body text generally looks nicer and is easier to read when the lines are spaced apart; the recommended line height is around 1.5 – 2 (double spaced.) So to set our lines of text to 1.6 times the height of the font, you’d use this:
line-height: 1.6;
h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p>
html font-size: 10px; > h1 font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; text-align: center; > h1 + p font-weight: bold; > p font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; line-height: 1.6; >
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:
p::first-line letter-spacing: 4px; word-spacing: 4px; >
Let’s add some to our example, like so:
h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p>
html font-size: 10px; > h1 font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; text-align: center; letter-spacing: 2px; > h1 + p font-weight: bold; > p::first-line letter-spacing: 4px; word-spacing: 4px; > p font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; line-height: 1.6; letter-spacing: 1px; >
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:
- font-variant (en-US): Switch between small caps and normal font alternatives.
- font-kerning (en-US): Switch font kerning options on and off.
- font-feature-settings (en-US): Switch various OpenType font features on and off.
- font-variant-alternates (en-US): Control the use of alternate glyphs for a given font-face.
- font-variant-caps (en-US): Control the use of alternate capital glyphs.
- font-variant-east-asian (en-US): Control the usage of alternate glyphs for East Asian scripts, like Japanese and Chinese.
- font-variant-ligatures : Control which ligatures and contextual forms are used in text.
- font-variant-numeric : Control the usage of alternate glyphs for numbers, fractions, and ordinal markers.
- font-variant-position (en-US): Control the usage of alternate glyphs of smaller sizes positioned as superscript or subscript.
- font-size-adjust (en-US): Adjust the visual size of the font independently of its actual font size.
- font-stretch (en-US): Switch between possible alternative stretched versions of a given font.
- text-underline-position (en-US): Specify the position of underlines set using the text-decoration-line property underline value.
- text-rendering (en-US): Try to perform some text rendering optimization.
Text layout styles:
- text-indent : Specify how much horizontal space should be left before the beginning of the first line of the text content.
- text-overflow (en-US): Define how overflowed content that is not displayed is signaled to users.
- white-space : Define how whitespace and associated line breaks inside the element are handled.
- word-break : Specify whether to break lines within words.
- direction : Define the text direction (This depends on the language and usually it’s better to let HTML handle that part as it is tied to the text content.)
- hyphens : Switch on and off hyphenation for supported languages.
- line-break : Relax or strengthen line breaking for Asian languages.
- text-align-last : Define how the last line of a block or a line, right before a forced line break, is aligned.
- text-orientation (en-US): Define the orientation of the text in a line.
- overflow-wrap : Specify whether or not the browser may break lines within words in order to prevent overflow.
- writing-mode : Define whether lines of text are laid out horizontally or vertically and the direction in which subsequent lines flow.
Font shorthand
Many font properties can also be set through the shorthand property font . These are written in the following order: font-style , font-variant (en-US), font-weight , font-stretch (en-US), font-size , line-height , and font-family .
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:
font: italic normal bold normal 3em/1.5 Helvetica, Arial, sans-serif;
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.
div class="body-wrapper" style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;"> h2>HTML Inputh2> textarea id="code" class="html-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"> p>Some sample text for your delightp> textarea> h2>CSS Inputh2> textarea id="code" class="css-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"> p < >textarea > h2>Outputh2> div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">div> div class="controls"> input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;" /> div> div>
const htmlInput = document.querySelector(".html-input"); const cssInput = document.querySelector(".css-input"); const reset = document.getElementById("reset"); let htmlCode = htmlInput.value; let cssCode = cssInput.value; const output = document.querySelector(".output"); const styleElem = document.createElement("style"); const headElem = document.querySelector("head"); headElem.appendChild(styleElem); function drawOutput() output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; > reset.addEventListener("click", function () htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput(); >); htmlInput.addEventListener("input", drawOutput); cssInput.addEventListener("input", drawOutput); window.addEventListener("load", drawOutput);
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.
In this module
- Fundamental text and font styling
- Styling lists
- Styling links
- Web fonts
- Typesetting a community school homepage
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on 3 авг. 2023 г. by MDN contributors.
Your blueprint for a better internet.
Как оформить текст: 11 главных CSS-свойств
У любого текстового элемента есть свои стили по умолчанию. Заголовки крупные и жирные, текст в абзацах нормального размера и начертания, а ссылки обычно синие и подчёркнутые снизу.
Каждый из этих элементов можно стилизовать по-своему, например, поменять размер, начертание или цвет. Давайте посмотрим, как это сделать.
Для каждого стиля мы подготовили пример в CodePen — попробуйте поменять значения и посмотрите, как изменится текст.
Сменить шрифт
Чтобы изменить шрифт элемента, используйте CSS-свойство font-family :
body
Первым указывается шрифт, который вы хотите добавить. После него через запятую идут альтернативные шрифты. Например, если на компьютере у посетителя сайта не установлен шрифт Roboto, браузер использует шрифт Arial.
Изменить цвет и размер текста
Цвет текста задаётся с помощью свойства color . Оно принимает значения в различных форматах: можно написать название цвета ( red , blue ), шестнадцатеричное значение ( #ff0000 , #00f ) или функцию rgb() , чтобы задать цвет с помощью трёх чисел.
Размер текста меняется свойством font-size . Оно принимает значения в пикселях ( px ), процентах ( % ) и других единицах измерения.
Добавить жирность
Свойство font-weight задаёт жирность текста. Оно принимает два вида значений.
Численные: от 100 до 900 . Например, 400 — обычный шрифт, а 700 — полужирный.
Ключевые слова: normal — обычный шрифт, bold — полужирный, bolder — жирнее, чем текущий, lighter — менее жирный шрифт по сравнению с текущим.
See the Pen Untitled by Feizerr on CodePen.
Сделать текст курсивным
Для этого есть свойство font-style . По умолчанию у него стоит значение normal , то есть текст обычный, без курсива. Чтобы поменять начертание, используйте:
- italic — делает текст курсивным;
- oblique — делает текст наклонным.
Оба значения создают похожий эффект — текст выглядит курсивным, но есть и разница. Если очень упростить, то italic и oblique немного отличаются в начертании. А ещё не у всех шрифтов есть специальная курсивная версия. В таких случаях oblique делает текст похожим на курсив.
See the Pen Как сделать курсивный текст by Feizerr on CodePen.
Преобразовать текст
Свойство text-transform меняет регистр текста. Оно принимает значения:
- none — без изменений, значение по умолчанию;
- uppercase — все буквы становятся прописными;
- lowercase — все буквы становятся строчными;
- capitalize — первая буква каждого слова находится в верхнем регистре.
See the Pen Как изменить text-decoration by Feizerr on CodePen.
Добавить подчёркивание
Свойство text-decoration добавляет тексту декоративные эффекты:
- overline создаёт линию над текстом,
- line-through делает текст зачёркнутым,
- underline добавляет подчёркивание.
По умолчанию у свойства стоит значение none — без оформления.
See the Pen Как добавить подчёркивание by Feizerr on CodePen.
Создать тень
Свойство text-shadow добавляет тексту тень. Оно принимает значение в таком формате:
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5) /*смещение по горизонтали, смещение по вертикали, радиус размытия, цвет тени */
See the Pen Как добавить тень тексту by Feizerr on CodePen.
Выровнять текст
Свойство text-align выравнивает текст по горизонтали. Оно принимает значения:
- left — влево;
- right — вправо;
- center — по центру;
- justify — выравнивание по ширине.
See the Pen Как выровнять текст by Feizerr on CodePen.
Изменить высоту строки и межбуквенное расстояние
Свойство line-height устанавливает высоту строки, указывая множитель относительно размера шрифта. Свойство letter-spacing управляет расстоянием между символами.
See the Pen Как изменить высоту строки by Feizerr on CodePen.
Нюансы
- У некоторых шрифтов нет жирного и курсивного варианта.
- Свойство text-shadow делает текст эффектным, но слишком насыщенные тени могут усложнить чтение текста или создать плохой контраст.
- Слишком большое или маленькое значение line-height и letter-spacing может нарушить интервалы между буквами и строками.
- При изменении размера шрифта ( font-size ) следует учитывать, что очень мелкий и крупный текст может плохо отображаться или стать нечитабельным.
Рекомендации
Тестируйте вёрстку. Проверяйте, как шрифты отображаются на разных устройствах и браузерах. Некоторые шрифты могут отображаться по-разному на разных платформах.
Используйте стили осторожно. Смена регистра, курсив и жирный текст помогают выделить важный контент, расставляют акценты в тексте. Используйте их умеренно, потому что крупные фрагменты текста, написанного капсом или курсивом, лишь отвлекают пользователя. Акценты теряются, и текст выглядит неаккуратно.
Помните о доступности. Используйте подходящие значения font-weight — слишком мелкий или крупный текст плохо читается. Подбирайте контрастные цвета для текстов.
Используйте несколько шрифтов. Некоторые шрифты могут быть недоступны, поэтому важно указывать альтернативные варианты.
Соблюдайте авторское право. У каждого шрифта есть лицензия, которая описывает, в каких случаях можно использовать шрифт, а в каких нельзя. Например, какие-то варианты нельзя использовать в коммерческих проектах, а какие-то предназначены только для веба или печати. Поэтому нужно внимательно читать лицензию перед загрузкой понравившегося шрифта — вдруг он не подходит под ваши цели.
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
Читать дальше
Увеличение ссылки при наведении
Задача: плавно увеличить ссылку при наведении.
Решение:
a < display: inline-block; transition: transform 0.3s ease; >a:hover
Вот как это работает:
Что всё это значит
Первые два свойства просто немного меняют вид ссылки.
Свойство color: maroon; меняет цвет текста в тегах на темно-красный.
Свойство text-decoration: none; убирает подчеркивание. Есть и другие варианты text-decoration — мы писали о них отдельно.
Но наша задача — плавно увеличить размер ссылки, а не просто её перекрасить. Поэтому работаем с CSS-анимацией. Так, свойство transform: scale(1.2); срабатывает при наведении курсора и увеличивает размер ссылки в 1.2 раза по сравнению с её начальным размером.
Свойство transition: transform 0.3s ease; используется для создания плавного перехода между состояниями элемента. В нашем случае увеличение будет происходить в течение 0.3 секунд с использованием функции времени ease для более плавного начала и конца анимации.
- 13 октября 2023
WOFF больше не нужен
Я купил и скачал шрифты для недавнего проекта, распаковал папку, где были только WOFF2-файлы, и сначала не поверил, что такое бывает.
Потом мне стало интересно: они что, забыли WOFF? А он вообще ещё нужен? Ну, всё-таки, веб — это место, где постоянно всё меняется и улучшается, поэтому я пошёл и спросил людей в Mastodon. Ответ был единодушным: нужен только WOFF2!
Я хорошо помню пост от Зака в конце 2016, после которого я отказался от исчерпывающего синтаксиса @font-face , включавшего, вдобавок, TTF, EOT и SVG-шрифты, и перешёл только на WOFF2 и WOFF.
Похоже, с тех пор мир веб-шрифтов изменился ещё разок, и вот актуальная версия @font-face :
@font-face
Остался всего один формат. Просто, скажите?
Как писал Зак, «так как в вебе, когда шрифт не найден, всё равно подгружаются системные шрифты, мы можем идти в ногу со временем». Итак, какие браузеры отправятся в тёмные века системных шрифтов с этим синтаксисом?
- IE 11, 10, 9, 8, 7, …
- Chrome 4–35
- Edge 12 и 13
- Safari 3–9.1
- Firefox 2–38
- Opera 22 и ниже
- Android 4.4.4 KitKat и ниже (а это
- Safari на iOS 3.2–9.3
Caniuse.com показывает, что почти у 95% пользователей есть браузер с поддержкой WOFF2. А в относительной статистике (Date Relative — прим. перев.) заметно, что массовый переход на WOFF2 случился в 2015 и 2016. К концу 2016 во всех последних версиях больших браузеров появилась поддержка WOFF2.3
А спустя 7 лет поддержка расширилась настолько, что можно уже не добавлять в проект WOFF-файлы — ну, кроме случая, когда вы точно знаете, что много ваших пользователей используют старые устройства и браузеры.
С другой стороны, нет смысла и удалять WOFF из старых проектов. Если вы подключали WOFF2 раньше WOFF внутри @font-face — и порядок здесь важен — то браузер просто скачает и подключит WOFF2-версию.
И если однажды вы, как и я, обнаружите себя перед папкой, полной файлов WOFF2, знайте, что WOFF — уже всё.
- 23 сентября 2023
Трясём пароль с помощью CSS
Знаете момент, когда всё на сайте уже сделано, и хочется добавить какую-нибудь маленькую незаметную фишку? Мы тоже знаем, поэтому давайте просто потрясём поле пароля, когда пользователь ввёл неверный пароль. Как на Маке.
Вот что получится в итоге:
- 7 сентября 2023
Как сделать тёмную тему на сайте
Без лишних слов создадим простой переключатель для светлой и темной темы с использованием HTML, CSS и JavaScript. Нам понадобятся три файла — index.html , styles.css и script.js .
HTML
Основная разметка страницы — заголовок, абзац текста, список и текст в рамке.
CSS (styles.css):
Здесь задаём цвета для светлой и тёмной темы, а ещё минимальную стилизацию текста и блока с рамкой.
body < font-family: Arial, sans-serif; transition: background-color 0.3s ease; >body.light-theme < background-color: #ffffff; color: #000000; >body.dark-theme < background-color: #121212; color: #ffffff; >.boxed-text
JavaScript (script.js)
Этот код нужен, чтобы переключать тему при нажатии на кнопку:
document.getElementById('themeToggle').addEventListener('click', function() < const currentTheme = document.body.className; if (currentTheme === 'light-theme') < document.body.className = 'dark-theme'; >else < document.body.className = 'light-theme'; >>);
При загрузке страницы по умолчанию будет установлена светлая тема. При нажатии на кнопку «Переключить тему» будет происходить переключение между светлой и темной темой.
- 29 августа 2023
4 способа центрировать текст в CSS
Центрирование элементов на веб-странице — это одна из наиболее распространенных задач, с которой мы сталкиваемся при работе с макетами. И хотя центрирование текста по горизонтали довольно простое ( text-align: center; и делов-то), вертикальное центрирование может быть немного сложнее. Давайте рассмотрим несколько методов.
Метод 1: Flexbox
Flexbox — это один из самых простых и эффективных способов центрирования.
Заворачиваем текст в с классом center-both :
Центрированный текст
.center-both
Метод 2: CSS Grid
HTML такой же, как в предыдущем примере. В CSS включаем гриды и используем свойство place-items со значением center :
.center-both
Метод 3: позиционирование и Transform
Этот метод немного старомодный и работает не идеально. Здесь у div устанавливается relative позиция. А
внутри дива мы сдвигаем с помощью абсолютного позиционирования. Не слишком элегантно:
.center-both < position: relative; >.center-both p
HTML остается таким же. Вот что получается:
Плохой метод: использование line-height
Если у вас однострочный текст, вы можете установить line-height , равный высоте родительского элемента.
.center-both < line-height: 200px; /* Пример высоты */ text-align: center; >
Этот метод не подойдет для многострочного текста. Да и вообще мы очень не рекомендуем так делать, это прям совсем для любителей острых ощущений. Потому что вот:
Если вам интересно узнать больше о каждом из этих методов, рекомендуем посмотреть документацию по Flexbox на MDN или документацию по CSS Grid на MDN, а ещё пройти курсы в HTML Academy.
- 28 августа 2023
Как скруглить рамку. CSS-свойство border-radius
CSS-свойство border-radius помогает скруглить углы элемента. Оно особенно полезно для стилизации кнопок, форм, карточек товаров и других элементов сайта.
- 28 июля 2023
CSS-свойство contain
Представьте, что у вас есть контейнер. Внутри него находятся разные элементы: текст, изображения или что-то другое. Свойство contain говорит браузеру, как именно элементы должны взаимодействовать. Например, они могут быть ограничены, влиять на расположение друг друга или менять свои размеры.
Также свойство помогает повысить производительность страницы. Например, браузер понимает, когда при изменении свойств элемента нужно перерисовать страницу, а когда нет.
⭐ CSS-свойство contain определяет, как элемент должен взаимодействовать с другими элементами внутри контейнера.
Синтаксис
.container
- 14 июля 2023
Как задать позицию и размер элемента. CSS-свойство inset
CSS-свойство inset задаёт позицию и размер элемента на странице. Это комбинация четырёх отдельных свойств: top , right , bottom и left , которые определяют отступы от верхнего, правого, нижнего и левого края элемента.
Синтаксис
.element
- 13 июля 2023
Как перекрыть один элемент другим. CSS-свойство z-index
z-index определяет порядок наложения элементов в трёхмерном пространстве на веб-странице. Свойство управляет тем, как элементы перекрывают друг друга, если они имеют позиционирование, отличное от значения static .
Синтаксис
.my-element
- 10 июля 2023
Как верстать и оформлять цитаты
Не используйте тег для других видов текста — перевода или шутки, так как это не семантично.
- 22 июня 2023