- Line height in javascript
- Свойства font-size и line-height
- font-size и line-height
- Множитель для line-height
- Style lineHeight Property
- Browser Support
- Syntax
- Property Values
- Technical Details
- More Examples
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Javascript Reference — HTML DOM Style lineHeight Property
- Browser Support
- Syntax
- Property Values
- Technical Details
- Example
- Example 2
- lineHeight style property
- Syntax:
- Possible values:
- Example HTML code 1:
- Example HTML code 2:
- Example HTML code 3:
- Supported by objects:
Line height in javascript
Calculate line-height of an HTML element (IE6 compatible)
This was created for provide a well-tested module for calculating line-height in pixels for trunkata, a line-based truncation library for HTML.
line-height is available via the following:
- npm, npm install line-height
- bower, bower install line-height
- component, component install line-height
- Download via HTTP
For npm and component , you can load it in as follows:
var lineHeight = require('line-height');
For bower and http , you can use vanilla JS
script src="components/line-height.js">/script>window.lineHeight; // `line-height` is defined on `window` in camelCase
require(['line-height'], funtion (lineHeight) /* code */ >);
or CommonJS syntax (see npm / component section).
Once you have the module loaded, you can get the line-height of any node in the DOM.
// Calculate the `line-height` of the bodylineHeight(document.body); // 19// Calculate the `line-height` of an h2var h2 = document.createElement('h2');document.body.appendChild(h2);lineHeight(h2); // 29// Calculate how many lines tall an element isvar div = document.createElement('div');div.innerHTML = '1
2
';(lineHeight(div) / div.offsetHeight); // 2, how trunkata performs its calculations
Support this project and others by twolfson via donations
line-height provides a single function.
lineHeight(node);/*** Calculate the `line-height` of a given node* @param node Element to calculate line height of. Must be in the DOM.* @returns `line-height` of the element in pixels*/
In a large amount of browsers, the computed style for an element’s line-height is normal by default.
If it is specified by any other means (e.g. ancestor has a line-height or the element has a line-height specified), it is either a CSS length.
To solve this problem, we create a vanilla element of the same nodeName (e.g. h2 if it is an h2 ), apply the original element’s font-size , and return the element offsetHeight . This is the height of 1 line of the element (i.e. line-height ).
Converting pt , pc , in , cm , mm to px
In most browsers, when the line-height is specified in pt , pc , in , cm or mm , the computedStyle value is in the same unit.
To solve this problem, we use the standard ratios of conversion to pixels to make a conversion to pixels.
- 3pt to 4px
- 1pc to 16px
- 1in to 96px
- 2.54cm to 96px
- 25.4mm to 96px
In IE6, numeric font-size s (e.g. font-size: 2.3 ) are returned without a unit.
To solve this problem, we treat this number as an em since it is relative as well. To do that, we set the element’s style to «numeric value» + «em» , compute and save the font-size , remove the temporary style. This conversion gives us the unit in pt which we know how to deal with from before.
Tests can be run once via:
npm test# Or with Karma directly via# npm run test-karma-single
Tests can also be run continuously via:
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint via npm run lint and test via npm test .
Copyright (c) 2013 Todd Wolfson
Licensed under the MIT license.
Свойства font-size и line-height
Здесь мы рассмотрим, как соотносятся размеры шрифта и строки, и как их правильно задавать.
font-size и line-height
- font-size – размер шрифта, в частности, определяющий высоту букв.
- line-height – высота строки.
Для наглядности посмотрим пример HTML, в котором шрифт и размер строки одинаковы:
Размер шрифта font-size – это абстрактное значение, которое привязано к шрифту, и даётся в типографских целях.
Обычно оно равно расстоянию от самой верхней границы букв до самой нижней, исключая «нижние хвосты» букв, таких как p , g . Как видно из примера выше, при размере строки, равном font-size , строка не будет размером точно «под букву».
В зависимости от шрифта, «хвосты» букв при этом могут вылезать, правые буквы Ё и р в примере выше пересекаются как раз поэтому.
В некоторых особо размашистых шрифтах «хвосты букв» могут быть размером с саму букву, а то и больше. Но это, всё же исключение.
Обычно размер строки делают чуть больше, чем шрифт.
По умолчанию в браузерах используется специальное значение line-height:normal .
Оно означает, что браузер может принимать решение о размере строки самостоятельно. Как правило, оно будет в диапазоне 1.1 — 1.25 , но стандарт не гарантирует этого, он говорит лишь, что оно должно быть «разумным» (дословно – англ. reasonable).
Множитель для line-height
Значение line-height можно указать при помощи px или em , но гораздо лучше – задать его числом.
Значение-число интерпретируется как множитель относительно размера шрифта. Например, значение с множителем line-height: 2 при font-size: 16px будет аналогично line-height: 32px (=16px*2) .
Однако, между множителем и точным значением есть одна существенная разница.
- Значение, заданное множителем, наследуется и применяется в каждом элементе относительно его размера шрифта. То есть, line-height: 2 означает, что высота строки будет равна удвоенному размеру шрифта, не важно какой шрифт.
- Значение, заданное в единицах измерения, запоминается и наследуется «как есть». Это означает, что line-height: 32px будет всегда жёстко задавать высоту строки, даже если шрифт во вложенных элементах станет больше или меньше текущего.
Давайте посмотрим, как это выглядит, на примерах:
стандартная строка шрифт в 2 раза больше
шрифт в 2 раза больше
Style lineHeight Property
The lineHeight property sets or returns the distance between lines in a text.
Browser Support
Syntax
Return the lineHeight property:
Set the lineHeight property:
Property Values
Value | Description |
---|---|
normal | Normal line height is used. This is default |
number | A number that will be multiplied with the current font size to set the line height |
length | Defines the line height in length units |
% | Defines the line height in % of the current font size |
initial | Sets this property to its default value. Read about initial |
inherit | Inherits this property from its parent element. Read about inherit |
Technical Details
Default Value: | normal |
---|---|
Return Value: | A String, representing the distance between lines in the text |
CSS Version | CSS1 |
More Examples
Example
Return the line height of a element:
Related Pages
COLOR PICKER
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.
Javascript Reference — HTML DOM Style lineHeight Property
The lineHeight property sets or gets the distance between text lines.
Browser Support
lineHeight | Yes | Yes | Yes | Yes | Yes |
Syntax
Return the lineHeight property:
var v = object.style.lineHeight
Set the lineHeight property:
object.style.lineHeight='normal|number|length|%|initial|inherit'
Property Values
Value | Description |
---|---|
normal | Default. Normal line height. |
number | multiply a number with font size as line height |
length | Set line height in length units |
% | Set the line height in percent of the current font size |
initial | Set to default value. |
inherit | Inherit from parent element. |
Technical Details
Default Value: | normal |
---|---|
Return Value: | A string representing the distance between text lines |
CSS Version | CSS1 |
Example
The following code shows how to set the line height.
!DOCTYPE html> html> body> !--from w w w. j a v a2 s . co m--> div >"myDiv"> This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. button type="button" onclick="myFunction()">test script> function myFunction() < document.getElementById("myDiv").style.lineHeight = "3"; >
The code above is rendered as follows:
Example 2
The following code shows how to get the line height.
!DOCTYPE html> html> body> div >"myDiv" style="line-height:450%;"> This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. !-- w w w.j a va 2 s . c o m--> button type="button" onclick="myFunction()">test script> function myFunction() < console.log(document.getElementById("myDiv").style.lineHeight); >
The code above is rendered as follows:
java2s.com | © Demo Source and Support. All rights reserved.
lineHeight style property
Syntax:
Possible values:
A floating point number, the height of the line is the specified number multiplied by the font size of the element. |
The height of the line in length units. For the supported length units, see the length page. |
The height of the line is the specified percentage of the font size of the element. |
Takes the value of this property from the computed style of the parent element. |
Default. Normal height is used. |
Example HTML code 1:
head> style> .example1 border: 1px solid blue; font-size: 14px; line-height: 14px; > .example2 border: 1px solid blue; font-size: 14px; line-height: 20px; > .example3 border: 1px solid blue; font-size: 14px; line-height: 30px; > style> head> body> div class="example1"> Sample multiline text br />with 14px line-height, font-size is 14px div> br /> div class="example2"> Sample multiline text br />with 20px line-height, font-size is 14px div> br /> div class="example3"> Sample multiline text br />with 30px line-height, font-size is 14px div> body>
Example HTML code 2:
This example illustrates the use of the line-height property, all of the three div elements have the same line height (24px, 120% of 20px, 1.2 * 20px):
head> style> .example1 border: 1px solid blue; font-size: 20px; line-height: 24px; > .example2 border: 1px solid blue; font-size: 20px; line-height: 120%; > .example3 border: 1px solid blue; font-size: 20px; line-height: 1.2; > style> head> body> div class="example1"> Sample multiline text br />with 24px line-height, font-size is 20px div> br /> div class="example2"> Sample multiline text br />with 120% line-height, font-size is 20px div> br /> div class="example3"> Sample multiline text br />with 12px line-height, font-size is 20px div> body>
Example HTML code 3:
head> script type="text/javascript"> function ChangeLineHeight (selectTag) // Returns the index of the selected option var whichSelected = selectTag.selectedIndex; // Returns the selected options values var height = selectTag.options[whichSelected].text; var anchor = document.getElementById ("myAnchor"); anchor.style.lineHeight = height; > script> head> body> a id="myAnchor" style="line-height: 1.2em"> Sample multiline text br />with the specified line-height a> br /> select onchange="ChangeLineHeight (this);" size="10"> option />0.2 option />0.5 option />0.8 option />1 option selected="selected" />1.2 option />1.5 option />1.8 option />2.1 option />2.4 option />3 select> body>