line-height

line-height

Устанавливает интерлиньяж (межстрочный интервал) текста, отсчет ведется от базовой линии шрифта. При обычных обстоятельствах расстояние между строками зависит от вида и размера шрифта и определяется браузером автоматически. Отрицательное значение межстрочного расстояния не допускается.

Синтаксис

line-height: множитель | значение | проценты | normal | inherit

Значения

Любое число больше нуля воспринимается как множитель от размера шрифта текущего текста. Например, значение 1.5 устанавливает полуторный межстрочный интервал. В качестве значений принимаются также любые единицы длины, принятые в CSS — пикселы (px), дюймы (in), пункты (pt) и др. Разрешается использовать процентную запись, в этом случае за 100% берется высота шрифта.

normal Расстояние между строк вычисляется автоматически. inherit Наследует значение родителя.

HTML5 CSS2.1 IE Cr Op Sa Fx

     h1 < line-height: 60%; >p 

Duis te feugifacilisi

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Результат данного примера показан на рис. 1.

Читайте также:  Excel to HTML Table | Javacodepoint

Применение свойства line-height

Рис. 1. Применение свойства line-height

Объектная модель

[window.]document.getElementById(» elementID «).style.lineHeight

Браузеры

Internet Explorer до версии 7.0 неправильно вычисляет высоту строк для изображений и элементов форм. Также в этом браузере не поддерживается значение inherit .

Источник

line-height

Устанавливает интерлиньяж (межстрочный интервал) текста, отсчет ведется от базовой линии шрифта. При обычных обстоятельствах расстояние между строками зависит от вида и размера шрифта и определяется браузером автоматически. Отрицательное значение межстрочного расстояния не допускается.

Синтаксис

line-height: множитель | значение | проценты | normal | inherit

Значения

Любое число больше нуля воспринимается как множитель от размера шрифта текущего текста. Например, значение 1.5 устанавливает полуторный межстрочный интервал. В качестве значений принимаются также любые единицы длины, принятые в CSS — пикселы (px), дюймы (in), пункты (pt) и др. Разрешается использовать процентную запись, в этом случае за 100% берется высота шрифта.

normal Расстояние между строк вычисляется автоматически. inherit Наследует значение родителя.

HTML5 CSS2.1 IE Cr Op Sa Fx

     h1 < line-height: 60%; >p 

Duis te feugifacilisi

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Результат данного примера показан на рис. 1.

Применение свойства line-height

Рис. 1. Применение свойства line-height

Объектная модель

[window.]document.getElementById(» elementID «).style.lineHeight

Браузеры

Internet Explorer до версии 7.0 неправильно вычисляет высоту строк для изображений и элементов форм. Также в этом браузере не поддерживается значение inherit .

Источник

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

Источник

line-height

Свойство CSS line-height устанавливает величину пространства между строками, например в тексте. В блочных элементах оно указывает минимальную высоту блоков строк внутри элемента. В незамещаемых внутристрочных элементах —указывает высоту, которая используется для вычисления высоты блоков строк.

Интерактивный пример

Синтаксис

/* Keyword value */ line-height: normal; /* Unitless values: use this number multiplied by the element's font size */ line-height: 3.5; /* values */ line-height: 3em; /* values */ line-height: 34%; /* Global values */ line-height: inherit; line-height: initial; line-height: unset; 

Свойство line-height задаётся с помощью:

Значения

Зависит от пользовательского браузера. Компьютерные браузеры (включая Firefox) используют значение по умолчанию приблизительно 1.2 , в зависимости от элементов font-family .

Значением line-height будет результат умножения указанного числа (без именования) на размер шрифта элементов. Указанное число, по сути, множитель. В большинстве случаев это предпочтительный способ указания значения line-height , потому что позволяет избежать непредвиденных результатов при наследовании.

Формальный синтаксис

Примеры

Basic example

/* All rules below have the same resultant line height */ div  line-height: 1.2; font-size: 10pt; > /* number */ div  line-height: 1.2em; font-size: 10pt; > /* length */ div  line-height: 120%; font-size: 10pt; > /* percentage */ div  font: 10pt/1.2 Georgia,"Bitstream Charter",serif; > /* font shorthand */ 

It is often more convenient to set line-height by using the font shorthand as shown above, but this requires the font-family property to be specified as well.

Prefer unitless numbers for line-height values

CSS

.green  line-height: 1.1; border: solid limegreen; > .red  line-height: 1.1em; border: solid red; > h1  font-size: 30px; > .box  width: 18em; display: inline-block; vertical-align: top; font-size: 15px; > 

HTML

div class="box green"> h1>Avoid unexpected results by using unitless line-height.h1> length and percentage line-heights have poor inheritance behavior . div> div class="box red"> h1>Avoid unexpected results by using unitless line-height.h1> length and percentage line-heights have poor inheritance behavior . div>  line-height is calculated from its own font-size (30px × 1.1) = 33px -->  line-height results from the red div's font-size (15px × 1.1) = 16.5px, probably not what you want --> 

Result

Specifications

Specification Status Comment
CSS Transitions
Определение ‘line-height’ в этой спецификации.
Рабочий черновик Defines line-height as animatable.
CSS Level 2 (Revision 1)
Определение ‘line-height’ в этой спецификации.
Рекомендация No change.
CSS Level 1
Определение ‘line-height’ в этой спецификации.
Рекомендация Initial definition.
Начальное значение normal
Применяется к все элементы. Это также применяется к ::first-letter и ::first-line .
Наследуется да
Проценты относятся к размеру шрифта самого элемента
Обработка значения для процентов и значений длин, абсолютной длины, если другое не указано
Animation type число или длина

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on 10 окт. 2022 г. by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

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.

Источник

Оцените статью