HTML 的換行技巧

Dian
Jun 27, 2021

--

攝影師:Miguel Á. Padriñán,連結:Pexels

本文記錄數種 HTML 常用的換行方式,並在文章底部提供簡單的範例。

換行元素

最基礎且常見的 <BR>,基本上沒什麼好介紹的,手刻流最佳選擇,想換行就換行。

CSS 換行

有很不同的換行設定,有 white-space, overflow-wrap, word-break 或最近才發現的 hyphens。

hyphens 會依據字典(註1)將斷行設定在較佳的位置上,並且加上 - 讓閱讀效果更好,在介面上出現過長的單字時非常適用,在底部的範例中可以看到原本的 Backgrounds 自動切斷為 Back-grounds ,比使用 overflow-wrap 斷成 Backgroun ds 好多了。

註1: 記得在 html element 加上正確的 lang code 的宣告 lang="xx",browser 才能在正確的位置斷字。如果網站上有多國語系有個很方便的工具可以幫你找到正確的 lang code,language subtag lookup

可觸發換行特殊字元

常見的有空格,短線 -或是看不見的 ZeroWidthSpace。

ZeroWidthSpace (&#8203;&ZeroWidthSpace;)
通常字串中的空格或是 - 再加上 CSS 的 hyphens 屬性就可以有正確的換行效果,但是總是有一些怪字(PM👽: 怪我囉?)。
像是在範例中使用斜線來分隔的字串 Vanilla/React/Vue/Angular 就算使用 css 的 hyphens 也無法正確換行,這種狀況就可以透過 JS 在指定的字串中加入 ZeroWidthSpace 字元,既不破壞原字串也可以達到換行效果,棒棒的💪。

最後附上簡單的範例。

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Dian
Dian

Written by Dian

學習>吸收>實作>再學習

No responses yet

Write a response