CSS 屬性line-height定義兩個內嵌元素之間的間距。典型用途是分隔文字。您可以看到人們將其與“前導”進行比較,“前導”是印刷術中使用的術語,指兩行文本的基線之間的空間。 line-height工作方式不同。它在文字上方和下方加入了空間。

行距與行高

左:行距,右:行高

用法

您可以使用具有不同值的line-height如下所示:

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

噢,孩子😧!好多啊。讓我們一一分析一下👍。

預設值和無單位值

如果您不將其設定為不同的值,則「正常」是預設值。通常,這意味著它設定為1.2 ,這取決於瀏覽器供應商。那麼只有一個數字值而沒有任何單位是什麼意思呢?它實際上是一個乘數。它採用font-size值並將其乘以1.2 。讓我們用下面的例子來計算一條線的高度。

body {
    font-size: 16px;
    line-height: 1.5;
}

我們只需要做以下計算:16 * 1.5 = 24px。現在我們知道文字的最小高度為 24 像素。因此它將在文字下方和上方加入 4 個像素。酷就這麼簡單😎!

em 和 rem

下一個是emremrem相對於根元素的font-sizeem相對於目前元素的 font-size。這是一個例子

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 */
}

百分比

%值有點難以閱讀。 100%意味著乘以1。再次舉例來說明這一點。

body {
    font-size: 12px;
}


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

像素(px)

對我來說最簡單也是最令人困惑的是px值。將其設為任何像素值都會將其精確地設定為該值。因此,如果您的font-size為 16px,並且您將line-height設為 12px,您的字體將比它所包裝的容器更大。一般來說,您應該盡量避免在行高中使用px值!

body {
    font-size: 16px;
}

.pixel {
    line-height: 12px;
}

一些最佳實踐

一般來說,我先將body元素中的font-sizeline-height設定為以下值。

body {
    font-size: 16px;
    line-height: 1.5;
}

由此,您可以建立所有其他樣式。我會盡量避免使用無單位數字以外的任何東西。另外,嘗試使用易於分割的font-size值,例如 16 或 12。這將有助於您在設計中保持平衡。您也可以在marginpadding中使用它。在腦中計算 16 * 1.5 比 13 * 1.5 更容易。然後您將永遠知道實際價值是多少。

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

當然,你可以嘗試一下,這些規則也會有例外,但我總是這樣開始。

資源

  • http://www.indesignskills.com/tutorials/leading-typography/

  • https://developer.mozilla.org/en-US/docs/Web/CSS/line-height

  • https://www.w3schools.com/cssref/pr_dim_line-height.asp

  • https://css-tricks.com/almanac/properties/l/line-height/

  • https://ux.stackexchange.com/questions/35270/is-there-an-optimal-font-size-line-height-ratio

謝謝閱讀!


原文出處:https://dev.to/lampewebdev/css-line-height-jjp

按讚的人:

共有 0 則留言