Line height css properties

line — height

line — height задаёт интервал между строчками текста, который называют интерлиньяж.

Примеры

Скопировать ссылку «Примеры» Скопировано

 .selector  line-height: normal;> .selector  line-height: normal; >      

Множитель — расстояние будет в 3.5 раза больше, чем размер текста:

 .selector  line-height: 3.5;> .selector  line-height: 3.5; >      

Условные единицы — значение, относительно стандартного интервала.
В данном случае, интервал будет в 3 раза больше интервала родительского элемента.

 .selector  line-height: 3em;> .selector  line-height: 3em; >      

Проценты — размер интервала высчитывается относительно размера шрифта:

 .selector  line-height: 34%;> .selector  line-height: 34%; >      

Как понять

Скопировать ссылку «Как понять» Скопировано

С помощью line — height можно выбрать, насколько большое расстояние будет между строчками текста. Обычно это расстояние немного больше, чем высота шрифта.

Браузеры понимают line — height по-своему: как высоту контейнера строки. Символы внутри образуют область контента, а участки между этой областью и границей контейнера и есть интерлиньяж. Такая особенность может легко запутать, ведь обычно расстояние между строчками измеряется по базовым линиям текста.

Иллюстрация свойства line-height

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Задать свойство line — height можно одним из нескольких значений. Самый предсказуемый вариант — с помощью числа. У свойства line — height не может быть отрицательного значения.

  • normal — значение по умолчанию. Немного отличается в разных браузерах, но, как правило, равно 1.2. Это значит, что расстояние между строчками будет равно размеру шрифта font — family , помноженному на 1.2.
  • число — число без единиц измерения. Например, значение 1.5 значит, что высота строчки будет равна размеру шрифта font — family , помноженному на 1.5.
  • длина — например, пиксели px , условные единицы шрифта em , дюймы in , пункты pt и так далее.
  • проценты — например, line — height : 120 % . За 100% берётся размера шрифта font — size .

Лучше задавать интерлиньяж числом, чтобы, при увеличении размера шрифта, увеличивалось и расстояние между строчками.

Задавать высоту строки в каких-то единицах измерения не самый лучший вариант, потому что тогда высота строки не подстраивается автоматически под размер шрифта и может выглядеть не так, как ожидается.

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 Самый надёжный способ задать интервал между строчками — с помощью числа, например, 1.5. При увеличении масштаба страницы этот интервал увеличится соответствующим образом.

💡 Для обычного текста чаще всего используют полуторный интервал line — height : 1 . 5 . С таким интервалом текст удобнее читать.

💡 Ещё один способ задать интервал между строк — шорткат font . При этом обязательно сразу указать семейство шрифтов font — family . Например:

 div  font: 10px/1.2 Georgia, "Bitstream Charter", serif;> div  font: 10px/1.2 Georgia, "Bitstream Charter", serif; >      

Ещё примеры

Скопировать ссылку «Ещё примеры» Скопировано

Попробуем задать одно и то же расстояние между строчками с помощью разных значений. Каждое значение будет умножаться на размер шрифта font — size :

 div  line-height: 1.2; font-size: 10px;> div  line-height: 1.2; font-size: 10px; >      
 div  line-height: 1.2em; font-size: 10px;> div  line-height: 1.2em; font-size: 10px; >      
 div  line-height: 120%; font-size: 10px;> div  line-height: 120%; font-size: 10px; >      

Другой пример показывает, почему лучше всего задавать расстояние между строчками с помощью числа.

Спойлер: простое число умножается на высоту шрифта того же элемента, а, например, значение em — на высоту шрифта родительского элемента:

   

Тут мы задали интервал с помощью числа 1.2

Оно умножается на размер шрифта этого же элемента. Это удобно и предсказуемо.

А здесь мы ввели 1.2em

Это значит, что 1.2 умножается на размер шрифта родительского элемента, в нашем случае
, а не на размер заголовка. Это вносит путаницу.
div class="box box_green"> h1>Тут мы задали интервал с помощью числа 1.2h1> Оно умножается на размер шрифта этого же элемента. Это удобно и предсказуемо. div> div class="box box_blue"> h1>А здесь мы ввели 1.2emh1> Это значит, что 1.2 умножается на размер шрифта родительского элемента, в нашем случае div>, а не на размер заголовка. Это вносит путаницу.div> div>
 h1  font-size: 30px;> .box  width: 18em; padding: 20px; display: inline-block; vertical-align: top; font-size: 15px;> .box_green  line-height: 1.2; background-color: #49a16c;> .box_blue  line-height: 1.2em; background-color: #1a5ad7;> h1  font-size: 30px; > .box  width: 18em; padding: 20px; display: inline-block; vertical-align: top; font-size: 15px; > .box_green  line-height: 1.2; background-color: #49a16c; > .box_blue  line-height: 1.2em; background-color: #1a5ad7; >      

На практике

Скопировать ссылку «На практике» Скопировано

Алёна Батицкая советует

Скопировать ссылку «Алёна Батицкая советует» Скопировано

🛠 Если при вёрстке макета вы видите в графическом редакторе межстрочное расстояние, заданное в пикселях, то не стоит переносить его в точности. В случае, если размер шрифта элемента изменится, то абсолютно заданное межстрочное расстояние не подстроится. А хотелось бы больше гибкости.

Используй следующую функцию для расчёта относительного интерлиньяжа:

line height / font size = относительный line-height

Если размер шрифта в Фотошопе равен 58px, а межстрочное расстояние — 86px, то результат будет таким:

При округлении получим значение 1 . 5 .

🛠 Если в Фотошопе интерлиньяж не указан (пустое поле), то он равен стандартному значению — 120%. Что аналогично 1.2 для вёрстки.

Источник

CSS line-height Property

The line-height property specifies the height of a line.

Note: Negative values are not allowed.

Default value: normal
Inherited: yes
Animatable: yes. Read about animatable Try it
Version: CSS1
JavaScript syntax: object.style.lineHeight=»30px» Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

CSS Syntax

Property Values

Value Description Demo
normal A normal line height. This is default Demo ❯
number A number that will be multiplied with the current font-size to set the line height Demo ❯
length A fixed line height in px, pt, cm, etc. Demo ❯
% A line height in percent of the current font size Demo ❯
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

More Examples

Example

Set the line height in pixels and centimeters for different elements:

Example

Set the line height as a number for different elements:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

CSS line-height Property

The line-height property defines the line-height. There are three situations:

  • On block level elements, the line-height property specifies the minimal line-height of line boxes in the element.
  • On non-replaced inline elements, the line-height property specifies the height which is used in the calculation of the line box height.
  • On replaced inline elements just like buttons or other input elements, the line-height property does not affect.

The line-height property sets the leading of lines of a text. If the line-height value is greater than the font-size value of an element, the difference will be the leading of text.

The line-height property has no effect when applying to inline elements: such as images, buttons, etc.

Initial Value normal
Applies to List items.
Inherited Yes.
Animatable Yes. Height of the lines is animatable.
Version CSS1
DOM Syntax object.style.lineHeight = «40px»;

Syntax

line-height: normal | number | length | initial | inherit;

Example of the line-height property:

html> html> head> title>Title of the document title> style> div < line-height: normal; > style> head> body> h2>Line-height property example h2> h3>line-height: normal (default) h3> div>This is a paragraph with a standard line-height. br> The standard line height in most browsers is about 110% to 120%. div> body> html>

Result

CSS line-height Property

Example of the line-height property with the «length» value:

html> html> head> title>Title of the document title> style> div < line-height: 10px; > style> head> body> h2>Line-height property example h2> h3>line-height: 10px h3> div>This is a paragraph with a specified line-height. br> The line height here is set to 10 pixels. div> body> html>

Example of the line-height property with the «percentage» value:

html> html> head> title>Title of the document title> style> div < line-height: 200%; > style> head> body> h2>Line-height property example h2> h2>line-height: 200% h2> div>This is a paragraph with a bigger line-height. br> The line height here is set to 200%. div> body> html>

Example of the line-height property with all the values:

html> html> head> title>Title of the document title> style> div.a < line-height: 1; > div.b < line-height: 50px; > div.c < line-height: 0.5cm; > div.d < line-height: 1cm; > div.e < line-height: 200%; > div.f < line-height: normal; > style> head> body> h2>Line-height property example h2> h3>line-height: 1 h3> div class="a">This is a paragraph with a specified line-height. br> The line height here is set to 1. div> h3>line-height: 50px h3> div class="b">This is a paragraph with a specified line-height. br> The line height here is set to 50 pixels. div> h3>line-height: 0.5cm h3> div class="c">This is a paragraph with a specified line-height. br> The line height here is set to 0.5 centimeter. div> h3>line-height: 1cm h3> div class="d">This is a paragraph with a specified line-height. br> The line height here is set to 1 centimeter. div> h3>line-height: 200% h3> div class="e">This is a paragraph with a bigger line-height. br> The line height here is set to 200%. div> h3>line-height: normal h3> div class="f">This is a paragraph with a standard line-height. br> The standard line height in most browsers is about 110% to 120%. div> body> html>

Line-height property for different purposes

The line-height property can be used for creating different interesting styles. For example, you can use the line-height property to give each line of the text a different color. Here you may use a linear-gradient () with color-stops. Or you can use this property for putting lines between texts with the help of repeating-linear-gradient().

Values

Value Description Play it
normal Defines a normal line height. It is the default value of this property. Play it »
length Defines a fixed line height in px, cm etc. Play it »
number Defines a number which is multiplied with the current font size to set the line height. Play it »
% Defines a line height in percent of current font size. Play it »
initial Makes the property use its default value. Play it »
inherit Inherits the property from its parents element.

Browser support

Источник

Читайте также:  If filename contains python
Оцените статью