line-height

line-height

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

Try it

Syntax

/ * Значение ключевого слова * / line-height: normal; / * Безразмерные значения: используйте это число, умноженное на размер шрифта элемента * / line-height: 3.5; / * значения * / line-height: 3em; / * значения * / line-height: 34%; / * Глобальные значения * / line-height: inherit; line-height: initial; line-height: revert; line-height: revert-layer; line-height: unset;

Свойство line-height указывается как одно из следующих:

Values

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

Устанавливает высоту линии в соответствии с высотой содержимого текущего блока.

Accessibility concerns

Используйте минимальное значение 1.5 для line-height для содержимого основного абзаца. Это поможет людям с плохим зрением, а также людям с когнитивными проблемами, такими как дислексия. Если страница увеличена для увеличения размера текста, использование значения без единиц измерения гарантирует, что высота линии будет пропорционально масштабироваться.

Formal definition

Initial value normal
Applies to все элементы. Это также относится к ::first-letter и ::first-line .
Inherited yes
Percentages указать размер шрифта самого элемента
Computed value для значений в процентах и длины,абсолютная длина,в противном случае как указано
Animation type номер или длина

Formal syntax

line-height = normal | number> | length-percentage> length-percentage> = length> | percentage> 

Examples

Basic example

/ * Все правила ниже имеют одинаковую результирующую высоту строки * / div < line-height: 1.2; font-size: 10pt; > / * число / без единицы измерения * / div < line-height: 1.2em; font-size: 10pt; > /* длина */ div < line-height: 120%; font-size: 10pt; > / * процент * / div < font: 10pt/1.2 Georgia,"Bitstream Charter",serif; > / * сокращение шрифта * / 

Часто удобнее устанавливать line-height , используя сокращение font как показано выше, но для этого также необходимо указать свойство font-family .

Предпочтение отдается безединичным номерам для значений высоты строки

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>  рассчитывается исходя из собственного размера шрифта (30px × 1.1) = 33px -->  получается из размера шрифта красного блока div (15px × 1.1) = 16,5px, возможно, это не то, что вам нужно --> 

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; >

Result

Specifications

Источник

line-height

The line-height CSS property sets the height of a line box. It’s commonly used to set the distance between lines of text. On block-level elements, it specifies the minimum height of line boxes within the element. On non-replaced inline elements, it specifies the height that is used to calculate line box height.

Try it

Syntax

/* 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: revert; line-height: revert-layer; line-height: unset; 

The line-height property is specified as any one of the following:

Values

Depends on the user agent. Desktop browsers (including Firefox) use a default value of roughly 1.2 , depending on the element’s font-family .

Accessibility concerns

Use a minimum value of 1.5 for line-height for main paragraph content. This will help people experiencing low vision conditions, as well as people with cognitive concerns such as Dyslexia. If the page is zoomed to increase the text size, using a unitless value ensures that the line height will scale proportionately.

Formal definition

Initial value normal
Applies to all elements. It also applies to ::first-letter and ::first-line .
Inherited yes
Percentages refer to the font size of the element itself
Computed value for percentage and length values, the absolute length, otherwise as specified
Animation type either number or length

Formal syntax

Examples

Basic example

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

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

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 --> 

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; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 7, 2023 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.

Источник

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 .

Источник

Читайте также:  Документ с фреймами
Оцените статью