line-height

line-height¶

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

Для остальных строчных элементов line-height задаёт высоту, которая используется для расчёта высоты строки блока.

Демо¶

  • font
  • font-family
  • font-feature-settings
  • font-kerning
  • font-language-override
  • font-optical-sizing
  • font-size
  • font-size-adjust
  • font-stretch
  • font-style
  • font-synthesis
  • font-variant
  • font-variant-alternates
  • font-variant-caps
  • font-variant-east-asian
  • font-variant-ligatures
  • font-variant-numeric
  • font-variant-position
  • font-variation-settings
  • font-weight
  • line-height

Синтаксис¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* 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; 

Значения¶

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

Читайте также:  Java about dialog example

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

Применяется ко всем элементам

Источник

CSS line-height – set minimum height of line box

On block level elements, the line-height property specifies the minimum height of line boxes within the element.

CSS property line-height

CSS version: CSS 2.1
Value: normal | number | length | percentage
Initial: normal
Applies to: all elements
Inherited: yes

line-height values

Value type Interpretation Inheritance
normal (default) roughly 1.2 depending upon font-family
number (preferred) number * font-size Value is inherited before computation
length (avoid) 1.2em, etc. Value is inherited after computation. Can lead to unexpected results
length (avoid) percentage * font-size Value is inherited after computation. Can lead to unexpected results

Comment on inheritance

In case font value is in number , the value is inherited as it is and computation applies on child element font-size. For value in length or percentage , it is computed and then inherited. In case child font being very large, this can lead to a situation line-height being less than font.

line-height number value example with inheritance

This is the preferred option and inheritance does not cause unexpected results.

 .outer < width: 100px; font-size: 14px; line-height: 1.2; >h1 
Hello world - just normal text

line-height length (em) value example with inheritance

When using line-height length (em) value, inheritance can cause expected results.

 .outer < width: 100px; font-size: 14px; line-height: 1.2em; >h1 
Hello world - just normal text

line-height percentage value example with inheritance

When using line-height percentage value, inheritance can cause expected results.

 .outer < width: 100px; font-size: 14px; line-height: 120%; >h1 
Hello world - just normal text

Источник

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.

Источник

Line-height CSS How CSS line-height works and best practices

leading vs line-height

The line-height CSS property defines the space between two inline elements. The typical use is, to space-out text. You can see people comparing it to ‘leading’ which is a term used in typography that refers to the space between the baseline of two lines of text. line-height works differently. It adds space above and under the text.
Left: Leading, Right: line-height

Usage

body  line-height: normal; /* default */ line-height: 2; line-height: 1em; line-height: 1rem; line-height: 200%; line-height: 20px; > 

Default value and unitless value

‘normal’ is the default value if you don’t set it to something different. Usually, this means that it is set to 1.2 , this depends on the browser vendor. So what does just a number value without any unit mean? It is actually a multiplier. It takes the font-size value and multiplies it by 1.2 . Let’s calculate the height of one line with the following example.

body  font-size: 16px; line-height: 1.5; > 

We just have to do the following calculation: 16 * 1.5 = 24px. So we now know that our text will have a minimum height of 24px. So it will add 4 pixels under the text and above it. Cool that easy 😎!

em and rem

Next one is em and rem . rem is relative to the font-size of the root element and em is relative to the current elements font-size. Here is an example

html  font-size: 12px; > .remExample  font-size: 16px; line-height: 1.5rem; /* line-height will be 12 * 1.5 = 18px */ > .emExample  font-size: 16px; line-height: 1.5em; /* line-height will be 16 * 1.5 = 24px */ > 

percentage

The % value is a little bit tricky to read. 100% means multiply by 1. Again an example to make it clear.

body  font-size: 12px; > .percentage  font-size: 16px; line-height: 150%; /* line-height will be 16 * 1.5 = 24px */ > 

pixel (px)

The easiest also most confusing one for me is the px value. Setting it to any pixel value will set it to exactly this value. So if your font-size for example is 16px and you set line-height to 12px your font will be bigger then the container it is wrapped in. In general, you should try to avoid using px values in line-height!

body  font-size: 16px; > .pixel  line-height: 12px; > 

Some best practices

In general, I would start with setting the font-size and line-height in the body element to the following values.

body  font-size: 16px; line-height: 1.5; > 

From this, you can build all your other stylings. I would try to avoid using anything else then unitless numbers. Also, try to use a value for the font-size that easily divided, like 16 or 12. This will help you to keep balance in your design. You can use this in margin s and padding s too. It’s easier to calculate 16 * 1.5 in your head then for example 13 * 1.5. You then will always know what the actual value is.

body  font-size: 16px; line-height: 1.5; > h1, h2, h3, h4, ul, ol  margin-bottom: 15rem; > button  display: inline-block; padding: 0.75rem 1.5rem; > 

Of course, you can experiment with this and there will be exceptions to these rules but this is how I always start.

Resources

Thanks for reading!

Источник

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 .

Источник

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