1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
|
---
title: Основы стилизирования текста и шрифта
slug: Learn/CSS/Styling_text/Fundamentals
translation_of: Learn/CSS/Styling_text/Fundamentals
---
<div>{{LearnSidebar}}</div>
<div>{{NextMenu("Learn/CSS/Styling_text/Styling_lists", "Learn/CSS/Styling_text")}}</div>
<p class="summary"><span class="seoSummary">В данной статье мы начнем путь к овладению стилизацией текста при помощи {{glossary("CSS")}}.</span> Мы подробно изучим основы стилизации текста и шрифта, такие как толщина, начертание, семейство, стенография, выравнивание текста и другие эффекты, а также рассмотрим междустрочный и межбуквенный интервалы.</p>
<table class="learn-box standard-table">
<tbody>
<tr>
<th scope="row">Необходимые знания:</th>
<td>Базовые компьютерные знания, Основы HTML (раздел <a href="/ru/docs/Learn/HTML/Введение_в_HTML">Введение в HTML</a>), основы CSS (раздел <a href="/ru/docs/Learn/CSS/First_steps">Введение в CSS</a>).</td>
</tr>
<tr>
<th scope="row">Задача:</th>
<td>Изучить основные свойства и техники, необходимые для стилизации текста на веб-страницах.</td>
</tr>
</tbody>
</table>
<h2 id="Что_участвует_в_стилизации_текста_в_CSS">Что участвует в стилизации текста в CSS?</h2>
<p>Как вы уже проверили в своей работе с HTML и CSS, текст внутри элемента выкладывается в поле содержимого элемента. Он начинается в левом верхнем углу области содержимого (или в правом верхнем углу, в случае содержимого языка RTL) и течет к концу строки. Как только он достигает конца, он переходит к следующей строке и продолжает, затем к следующей строке, пока все содержимое не будет помещено в коробку. Текстовое содержимое эффективно ведет себя как ряд встроенных элементов, размещенных на соседних строках и не создающих разрывы строк до тех пор, пока не будет достигнут конец строки, или если вы не принудите разрыв строки вручную с помощью элемента {{htmlelement("br")}}.</p>
<div class="note">
<p><strong>Примечание:</strong> если приведенный выше абзац оставляет вас в замешательстве, то не имеет значения — вернитесь и просмотрите нашу статью о модели коробки, чтобы освежить теорию модели коробки, прежде чем продолжить.</p>
</div>
<p>Свойства CSS, используемые для стилизации текста, обычно делятся на две категории, которые мы рассмотрим отдельно в этой статье:</p>
<ul>
<li><strong>Font styles</strong>: Свойства, влияющие на шрифт, применяемый к тексту, влияющие на то, какой шрифт применяется, насколько он велик, является ли он полужирным, курсивным и т. д.</li>
<li><strong>Text layout styles</strong>: Свойства, влияющие на интервал и другие особенности компоновки текста, позволяющие манипулировать, например, пространством между строками и буквами, а также тем, как текст выравнивается в поле содержимого.</li>
</ul>
<div class="note">
<p><strong>Примечание:</strong> имейте в виду, что текст внутри элемента все затронуты как одна единая сущность. Вы не можете выбирать и стилизовать подразделы текста, если вы не обернете их в соответствующий элемент (например, {{htmlelement ("span")}} или {{htmlelement ("strong")}}), или использовать текстовый псевдоэлемент, такой как ::first-letter (выделяет первую букву текста элемента),:: first-line (выделяет первую строку текста элемента) или ::selection (выделяет текст, выделенный в данный момент курсором.)</p>
</div>
<h2 id="Шрифты">Шрифты</h2>
<p>Давайте сразу перейдем к рассмотрению свойств для стилизации шрифтов. В этом примере мы применим некоторые различные свойства CSS к одному и тому же образцу HTML, который выглядит следующим образом:</p>
<pre class="brush: html notranslate"><h1>Tommy the cat</h1>
<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></pre>
<p>You can find the <a href="http://mdn.github.io/learning-area/css/styling-text/fundamentals/">finished example on GitHub</a> (see also <a href="https://github.com/mdn/learning-area/blob/master/css/styling-text/fundamentals/index.html">the source code</a>.)</p>
<h3 id="Color">Color</h3>
<p>The {{cssxref("color")}} 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 {{cssxref("text-decoration")}} property).</p>
<p><code>color</code> can accept any <a href="/en-US/Learn/CSS/Introduction_to_CSS/Values_and_units#Colors">CSS color unit</a>, for example:</p>
<pre class="brush: css notranslate">p {
color: red;
}</pre>
<p>This will cause the paragraphs to become red, rather than the standard browser default black, like so:</p>
<div class="hidden">
<pre class="brush: html notranslate"><h1>Tommy the cat</h1>
<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></pre>
</div>
<p>{{ EmbedLiveSample('Color', '100%', 230) }}</p>
<h3 id="Font_families">Font families</h3>
<p>To set a different font on your text, you use the {{cssxref("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 {{anch("Default fonts", "default font")}}. A simple example looks like so:</p>
<pre class="brush: css notranslate">p {
font-family: arial;
}</pre>
<p>This would make all paragraphs on a page adopt the arial font, which is found on any computer.</p>
<h4 id="Web_safe_fonts">Web safe fonts</h4>
<p>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 <strong>web safe fonts</strong>.</p>
<p>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).</p>
<p>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 <em><a href="https://en.wikipedia.org/wiki/Core_fonts_for_the_Web">Core fonts for the Web</a></em> initiative in the late 90s and early 2000s):</p>
<table class="standard-table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col" style="white-space: nowrap;">Generic type</th>
<th scope="col">Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td>Arial</td>
<td>sans-serif</td>
<td>It's often considered best practice to also add <em>Helvetica</em> as a preferred alternative to <em>Arial</em> as, although their font faces are almost identical, <em>Helvetica</em> is considered to have a nicer shape, even if <em>Arial</em> is more broadly available.</td>
</tr>
<tr>
<td>Courier New</td>
<td>monospace</td>
<td>Some OSes have an alternative (possibly older) version of the <em>Courier New</em> font called <em>Courier</em>. It's considered best practice to use both with <em>Courier New</em> as the preferred alternative.</td>
</tr>
<tr>
<td style="white-space: nowrap;">Georgia</td>
<td>serif</td>
<td></td>
</tr>
<tr>
<td style="white-space: nowrap;">Times New Roman</td>
<td>serif</td>
<td>Some OSes have an alternative (possibly older) version of the <em>Times New Roman</em> font called <em>Times</em>. It's considered best practice to use both with <em>Times New Roman</em> as the preferred alternative.</td>
</tr>
<tr>
<td>Trebuchet MS</td>
<td>sans-serif</td>
<td>You should be careful with using this font — it isn't widely available on mobile OSes.</td>
</tr>
<tr>
<td>Verdana</td>
<td>sans-serif</td>
<td></td>
</tr>
</tbody>
</table>
<div class="note">
<p><strong>Note</strong>: Among various resources, the <a href="http://www.cssfontstack.com/">cssfontstack.com</a> 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.</p>
</div>
<div class="note">
<p><strong>Note</strong>: 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: <strong>web fonts</strong>. This is a little bit more complex, and we will be discussing this in a <a href="/en-US/docs/Learn/CSS/Styling_text/Web_fonts">separate article</a> later on in the module.</p>
</div>
<h4 id="Default_fonts">Default fonts</h4>
<p>CSS defines five generic names for fonts: <code>serif</code><font face="Open Sans, Arial, sans-serif">, </font><code>sans-serif</code>,<font face="Open Sans, Arial, sans-serif"> </font><code>monospace</code>, <code>cursive</code> and <code>fantasy</code>. 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 <em>worst case scenario</em> where the browser will try to do its best to provide at least a font that looks appropriate. <code>serif</code>, <code>sans-serif</code> and <code>monospace</code> are quite predictable and should provide something reasonable. On the other hand, <code>cursive</code> and <code>fantasy</code> are less predictable and we recommend using them very carefully, testing as you go.</p>
<p>The five names are defined as follows:</p>
<table class="standard-table">
<thead>
<tr>
<th scope="col">Term</th>
<th scope="col">Definition</th>
<th scope="col">Example</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>serif</code></td>
<td>Fonts that have serifs (the flourishes and other small details you see at the ends of the strokes in some typefaces)</td>
<td><span style="font-family: serif;">My big red elephant</span></td>
</tr>
<tr>
<td><code>sans-serif</code></td>
<td>Fonts that don't have serifs.</td>
<td><span style="font-family: sans-serif;">My big red elephant</span></td>
</tr>
<tr>
<td><code>monospace</code></td>
<td>Fonts where every character has the same width, typically used in code listings.</td>
<td><span style="font-family: monospace;">My big red elephant</span></td>
</tr>
<tr>
<td><code>cursive</code></td>
<td>Fonts that are intended to emulate handwriting, with flowing, connected strokes.</td>
<td><span style="font-family: cursive;">My big red elephant</span></td>
</tr>
<tr>
<td><code>fantasy</code></td>
<td>Fonts that are intended to be decorative.</td>
<td><span style="font-family: fantasy;">My big red elephant</span></td>
</tr>
</tbody>
</table>
<h4 id="Font_stacks">Font stacks</h4>
<p>Since you can't guarantee the availability of the fonts you want to use on your webpages (even a web font <em>could</em> fail for some reason), you can supply a <strong>font stack</strong> so that the browser has multiple fonts it can choose from. This simply involves a <code>font-family</code> value consisting of multiple font names separated by commas, e.g.</p>
<pre class="brush: css notranslate">p {
font-family: "Trebuchet MS", Verdana, sans-serif;
}</pre>
<p>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.</p>
<p>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!</p>
<div class="note">
<p><strong>Note</strong>: Font names that have more than one word — like <code>Trebuchet MS</code> — need to be surrounded by quotes, for example <code>"Trebuchet MS"</code>.</p>
</div>
<h4 id="A_font-family_example">A font-family example</h4>
<p>Let's add to our previous example, giving the paragraphs a sans-serif font:</p>
<pre class="brush: css notranslate">p {
color: red;
font-family: Helvetica, Arial, sans-serif;
}</pre>
<p>This gives us the following result:</p>
<div class="hidden">
<pre class="brush: html notranslate"><h1>Tommy the cat</h1>
<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></pre>
</div>
<p>{{ EmbedLiveSample('A_font-family_example', '100%', 220) }}</p>
<h3 id="Font_size">Font size</h3>
<p>In our previous module's <a href="/en-US/docs/Learn/CSS/Building_blocks/Values_and_units">CSS values and units</a> article, we reviewed length and size units. Font size (set with the {{cssxref("font-size")}} property) can take values measured in most of these units (and others, such as <a href="/en-US/Learn/CSS/Introduction_to_CSS/Values_and_units#Percentages">percentages</a>), however the most common units you'll use to size text are:</p>
<ul>
<li><code>px</code> (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.</li>
<li><code>em</code>s: 1 <code>em</code> 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 <code>em</code> to size everything, not just text. You can have an entire website sized using <code>em</code>, which makes maintenance easy.</li>
<li><code>rem</code>s: These work just like <code>em</code>, except that 1 <code>rem</code> is equal to the font size set on the root element of the document (i.e. {{htmlelement("html")}}), 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 — <code>rem</code> is not supported in Internet Explorer 8 and below.</li>
</ul>
<p>The <code>font-size</code> of an element is inherited from that element's parent element. This all starts with the root element of the entire document — {{htmlelement("html")}} — the <code>font-size</code> of which is set to 16<code>px</code> 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 <code>px</code>. Other elements may have different default sizes, for example an {{htmlelement("h1")}} element has a size of 2 <code>em</code> set by default, so it will have a final size of 32 <code>px</code>.</p>
<p>Things become more tricky when you start altering the font size of nested elements. For example, if you had an {{htmlelement("article")}} element in your page, and set its <code>font-size</code> to 1.5 <code>em</code> (which would compute to 24 <code>px</code> final size), and then wanted the paragraphs inside the <code><article></code> elements to have a computed font size of 20 <code>px</code>, what <code>em</code> value would you use?</p>
<pre class="brush: html notranslate"><!-- document base font-size is 16px -->
<article> <!-- If my font-size is 1.5em -->
<p>My paragraph</p> <!-- How do I compute to 20px font-size? -->
</article></pre>
<p>You would need to set its <code>em</code> value to 20/24, or 0.83333333 <code>em</code>. The maths can be complicated, so you need to be careful about how you style things. It is best to use <code>rem</code> where you can, to keep things simple, and avoid setting the <code>font-size</code> of container elements where possible.</p>
<h4 id="A_simple_sizing_example">A simple sizing example</h4>
<p>When sizing your text, it is usually a good idea to set the base <code>font-size</code> of the document to 10 <code>px</code>, so that then the maths is a lot easier to work out — required <code>(r)em</code> 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 <code>font-size</code> rulesets in a designated area in your stylesheet, so they are easy to find.</p>
<p>Our new result is like so:</p>
<div class="hidden">
<pre class="brush: html notranslate"><h1>Tommy the cat</h1>
<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>
</pre>
</div>
<pre class="brush: css notranslate">html {
font-size: 10px;
}
h1 {
font-size: 5rem;
}
p {
font-size: 1.5rem;
color: red;
font-family: Helvetica, Arial, sans-serif;
}</pre>
<p>{{ EmbedLiveSample('A_simple_sizing_example', '100%', 260) }}</p>
<h3 id="Font_style_font_weight_text_transform_and_text_decoration">Font style, font weight, text transform, and text decoration</h3>
<p>CSS provides four common properties to alter the visual weight/emphasis of text:</p>
<ul>
<li>{{cssxref("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):
<ul>
<li><code>normal</code>: Sets the text to the normal font (turns existing italics off.)</li>
<li><code>italic</code>: Sets the text to use the <em>italic version of the font</em> if available; if not available, it will simulate italics with oblique instead.</li>
<li><code>oblique</code>: Sets the text to use a simulated version of an italic font, created by <span style="font-style: oblique;">slanting the normal version</span>.</li>
</ul>
</li>
<li>{{cssxref("font-weight")}}: Sets how bold the text is. This has many values available in case you have many font variants available (such as <em>-light</em>, <em>-normal</em>, <em>-bold</em>, <em>-extrabold</em>, <em>-black</em>, etc.), but realistically you'll rarely use any of them except for <code>normal</code> and <code>bold</code>:
<ul>
<li><code>normal</code>, <code>bold</code>: Normal and <strong style="font-weight: bold;">bold</strong> font weight</li>
<li><code>lighter</code>, <code>bolder</code>: Sets the current element's boldness to be one step lighter or heavier than its parent element's boldness.</li>
<li><code>100</code>–<code>900</code>: Numeric boldness values that provide finer grained control than the above keywords, if needed. </li>
</ul>
</li>
<li>{{cssxref("text-transform")}}: Allows you to set your font to be transformed. Values include:
<ul>
<li><code>none</code>: Prevents any transformation.</li>
<li><code>uppercase</code>: Transforms <span style="text-transform: uppercase;">all text to capitals</span>.</li>
<li><code>lowercase</code>: Transforms all text to lower case.</li>
<li><code>capitalize</code>: Transforms all words to <span style="text-transform: capitalize;">have the first letter capitalized</span>.</li>
<li><code>full-width</code>: Transforms all glyphs to be <span style="text-transform: full-width;">written inside a fixed-width square</span>, similar to a monospace font, allowing aligning of e.g. Latin characters along with Asian language glyphs (like Chinese, Japanese, Korean).</li>
</ul>
</li>
<li>{{cssxref("text-decoration")}}: Sets/unsets text decorations on fonts (you'll mainly use this to unset the default underline on links when styling them.) Available values are:
<ul>
<li><code>none</code>: Unsets any text decorations already present.</li>
<li><code>underline</code>: <u>Underlines the text</u>.</li>
<li><code>overline</code>: <span style="text-decoration: overline;">Gives the text an overline</span>.</li>
<li><code>line-through</code>: Puts a <s style="text-decoration: line-through;">strikethrough over the text</s>.</li>
</ul>
You should note that {{cssxref("text-decoration")}} can accept multiple values at once, if you want to add multiple decorations simultaneously, for example <span style="text-decoration: underline overline;"><code>text-decoration: underline overline</code></span>. Also note that {{cssxref("text-decoration")}} is a shorthand property for {{cssxref("text-decoration-line")}}, {{cssxref("text-decoration-style")}}, and {{cssxref("text-decoration-color")}}. You can use combinations of these property values to create interesting effects, for example <span style="text-decoration: line-through red wavy;"><code>text-decoration: line-through red wavy</code>.</span></li>
</ul>
<p>Let's look at adding a couple of these properties to our example:</p>
<p>Our new result is like so:</p>
<div class="hidden">
<pre class="brush: html notranslate"><h1>Tommy the cat</h1>
<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>
</pre>
</div>
<pre class="brush: css notranslate">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;
}</pre>
<p>{{ EmbedLiveSample('Font_style_font_weight_text_transform_and_text_decoration', '100%', 260) }}</p>
<h3 id="Text_drop_shadows">Text drop shadows</h3>
<p>You can apply drop shadows to your text using the {{cssxref("text-shadow")}} property. This takes up to four values, as shown in the example below:</p>
<pre class="brush: css notranslate">text-shadow: 4px 4px 5px red;</pre>
<p>The four properties are as follows:</p>
<ol>
<li>The horizontal offset of the shadow from the original text — this can take most available CSS <a href="/en-US/Learn/CSS/Introduction_to_CSS/Values_and_units#Length_and_size">length and size units</a>, but you'll most commonly use <code>px</code>; positive values move the shadow right, and negative values left. This value has to be included.</li>
<li>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.</li>
<li>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 <a href="/en-US/Learn/CSS/Introduction_to_CSS/Values_and_units#Length_and_size">length and size units</a>.</li>
<li>The base color of the shadow, which can take any <a href="/en-US/Learn/CSS/Introduction_to_CSS/Values_and_units#Colors">CSS color unit</a>. If not included, it defaults to <code>black</code>.</li>
</ol>
<h4 id="Multiple_shadows">Multiple shadows</h4>
<p>You can apply multiple shadows to the same text by including multiple shadow values separated by commas, for example:</p>
<pre class="brush: css notranslate">text-shadow: 1px 1px 1px red,
2px 2px 1px red;</pre>
<p>If we applied this to the {{htmlelement("h1")}} element in our Tommy the cat example, we'd end up with this:</p>
<div class="hidden">
<h5 id="Hidden_example1">Hidden example1</h5>
<pre class="brush: html notranslate"><h1>Tommy the cat</h1>
<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>
</pre>
<pre class="brush: css notranslate">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;
}</pre>
</div>
<p>{{ EmbedLiveSample('Hidden_example1', '100%', 260) }}</p>
<div class="note">
<p><strong>Note</strong>: You can see more interesting examples of <code>text-shadow</code> usage in the Sitepoint article <a href="http://www.sitepoint.com/moonlighting-css-text-shadow/">Moonlighting with CSS text-shadow</a>.</p>
</div>
<h2 id="Text_layout">Text layout</h2>
<p>With basic font properties out the way, let's now have a look at properties we can use to affect text layout.</p>
<h3 id="Text_alignment">Text alignment</h3>
<p>The {{cssxref("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:</p>
<ul>
<li><code>left</code>: Left-justifies the text.</li>
<li><code>right</code>: Right-justifies the text.</li>
<li><code>center</code>: Centers the text.</li>
<li><code>justify</code>: 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 {{cssxref("hyphens")}}, to break some of the longer words across lines.</li>
</ul>
<p>If we applied <code>text-align: center;</code> to the {{htmlelement("h1")}} in our example, we'd end up with this:</p>
<div class="hidden">
<pre class="brush: html notranslate"><h1>Tommy the cat</h1>
<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>
</pre>
<pre class="brush: css notranslate">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;
}</pre>
</div>
<p>{{ EmbedLiveSample('Text_alignment', '100%', 260) }}</p>
<h3 id="Line_height">Line height</h3>
<p>The {{cssxref("line-height")}} property sets the height of each line of text — this can take most <a href="/en-US/Learn/CSS/Introduction_to_CSS/Values_and_units#Length_and_size">length and size units</a>, but can also take a unitless value, which acts as a multiplier and is generally considered the best option — the {{cssxref("font-size")}} is multiplied to get the <code>line-height</code>. 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:</p>
<pre class="brush: css notranslate">line-height: 1.6;</pre>
<p>Applying this to the {{htmlelement("p")}} elements in our example would give us this result:</p>
<div class="hidden">
<h5 id="Hidden_example2">Hidden example2</h5>
<pre class="brush: html notranslate"><h1>Tommy the cat</h1>
<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>
</pre>
<pre class="brush: css notranslate">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;
}</pre>
</div>
<p>{{ EmbedLiveSample('Hidden_example2', '100%', 300) }}</p>
<h3 id="Letter_and_word_spacing">Letter and word spacing</h3>
<p>The {{cssxref("letter-spacing")}} and {{cssxref("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 <a href="/en-US/Learn/CSS/Introduction_to_CSS/Values_and_units#Length_and_size">length and size units</a>.</p>
<p>So as an example, we could apply some word- and letter-spacing to the first line of each {{htmlelement("p")}} element in our example:</p>
<pre class="brush: css notranslate">p::first-line {
letter-spacing: 4px;
word-spacing: 4px;
}</pre>
<p>Let's add some to our example, like so:</p>
<div class="hidden">
<pre class="brush: html notranslate"><h1>Tommy the cat</h1>
<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>
</pre>
<pre class="brush: css notranslate">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;
}</pre>
</div>
<p>{{ EmbedLiveSample('Letter_and_word_spacing', '100%', 330) }}</p>
<h3 id="Other_properties_worth_looking_at">Other properties worth looking at</h3>
<p>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:</p>
<p>Font styles:</p>
<ul>
<li>{{cssxref("font-variant")}}: Switch between small caps and normal font alternatives.</li>
<li>{{cssxref("font-kerning")}}: Switch font kerning options on and off.</li>
<li>{{cssxref("font-feature-settings")}}: Switch various <a href="https://en.wikipedia.org/wiki/OpenType">OpenType</a> font features on and off.</li>
<li>{{cssxref("font-variant-alternates")}}: Control the use of alternate glyphs for a given font-face.</li>
<li>{{cssxref("font-variant-caps")}}: Control the use of alternate capital glyphs.</li>
<li>{{cssxref("font-variant-east-asian")}}: Control the usage of alternate glyphs for East Asian scripts, like Japanese and Chinese.</li>
<li>{{cssxref("font-variant-ligatures")}}: Control which ligatures and contextual forms are used in text.</li>
<li>{{cssxref("font-variant-numeric")}}: Control the usage of alternate glyphs for numbers, fractions, and ordinal markers.</li>
<li>{{cssxref("font-variant-position")}}: Control the usage of alternate glyphs of smaller sizes positioned as superscript or subscript.</li>
<li>{{cssxref("font-size-adjust")}}: Adjust the visual size of the font independently of its actual font size.</li>
<li>{{cssxref("font-stretch")}}: Switch between possible alternative stretched versions of a given font.</li>
<li>{{cssxref("text-underline-position")}}: Specify the position of underlines set using the <code>text-decoration-line</code> property <code>underline</code> value.</li>
<li>{{cssxref("text-rendering")}}: Try to perform some text rendering optimization.</li>
</ul>
<p>Text layout styles:</p>
<ul>
<li>{{cssxref("text-indent")}}: Specify how much horizontal space should be left before the beginning of the first line of the text content.</li>
<li>{{cssxref("text-overflow")}}: Define how overflowed content that is not displayed is signaled to users.</li>
<li>{{cssxref("white-space")}}: Define how whitespace and associated line breaks inside the element are handled.</li>
<li>{{cssxref("word-break")}}: Specify whether to break lines within words.</li>
<li>{{cssxref("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.)</li>
<li>{{cssxref("hyphens")}}: Switch on and off hyphenation for supported languages.</li>
<li>{{cssxref("line-break")}}: Relax or strengthen line breaking for Asian languages.</li>
<li>{{cssxref("text-align-last")}}: Define how the last line of a block or a line, right before a forced line break, is aligned.</li>
<li>{{cssxref("text-orientation")}}: Define the orientation of the text in a line.</li>
<li>{{cssxref("overflow-wrap")}}: Specify whether or not the browser may break lines within words in order to prevent overflow.</li>
<li>{{cssxref("writing-mode")}}: Define whether lines of text are laid out horizontally or vertically and the direction in which subsequent lines flow.</li>
</ul>
<h2 id="Font_shorthand">Font shorthand</h2>
<p>Many font properties can also be set through the shorthand property {{cssxref("font")}}. These are written in the following order: {{cssxref("font-style")}}, {{cssxref("font-variant")}}, {{cssxref("font-weight")}}, {{cssxref("font-stretch")}}, {{cssxref("font-size")}}, {{cssxref("line-height")}}, and {{cssxref("font-family")}}.</p>
<p>Among all those properties, only <code>font-size</code> and <code>font-family</code> are required when using the <code>font</code> shorthand property.</p>
<p>A forward slash has to be put in between the {{cssxref("font-size")}} and {{cssxref("line-height")}} properties.</p>
<p>A full example would look like this:</p>
<pre class="brush: css notranslate">font: italic normal bold normal 3em/1.5 Helvetica, Arial, sans-serif;</pre>
<h2 id="Active_learning_Playing_with_styling_text">Active learning: Playing with styling text</h2>
<p>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.</p>
<p>If you make a mistake, you can always reset it using the <em>Reset</em> button.</p>
<div class="hidden">
<h6 id="Playable_code">Playable code</h6>
<pre class="brush: html notranslate"><div class="body-wrapper" style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;">
<h2>HTML Input</h2>
<textarea id="code" class="html-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">
<p>Some sample text for your delight</p>
</textarea>
<h2>CSS Input</h2>
<textarea id="code" class="css-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">
p {
}
</textarea>
<h2>Output</h2>
<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>
</pre>
<pre class="brush: js notranslate">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);
</pre>
</div>
<p>{{ EmbedLiveSample('Playable_code', 700, 800) }}</p>
<h2 id="Test_your_skills!">Test your skills!</h2>
<p>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 <a href="/en-US/docs/Learn/CSS/Styling_text/Typesetting_a_homepage">Typesetting a community school homepage</a>.</p>
<p>This assessment tests all the knowledge discussed in this module, so you might want to read the other articles before moving on to it.</p>
<h2 id="Summary">Summary</h2>
<p>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.</p>
<p>{{NextMenu("Learn/CSS/Styling_text/Styling_lists", "Learn/CSS/Styling_text")}}</p>
<h2 id="In_this_module">In this module</h2>
<ul>
<li><a href="/en-US/docs/Learn/CSS/Styling_text/Fundamentals">Fundamental text and font styling</a></li>
<li><a href="/en-US/docs/Learn/CSS/Styling_text/Styling_lists">Styling lists</a></li>
<li><a href="/en-US/docs/Learn/CSS/Styling_text/Styling_links">Styling links</a></li>
<li><a href="/en-US/docs/Learn/CSS/Styling_text/Web_fonts">Web fonts</a></li>
<li><a href="/en-US/Learn/CSS/Styling_text/Typesetting_a_homepage">Typesetting a community school homepage</a></li>
</ul>
|