網頁文字的祕密

NancyJY發表於2019-05-06

大家知道為什麼90%的網站上的文字都是從左到右整齊的排列著,像這樣

網頁文字的祕密

而不是從右到左,或是從上到下,或是呈鋸齒形,或是八字路,或是就這樣隨心所欲的寫...

網頁文字的祕密
其實這是由CSS本身的規則以及前端開發人員設定的屬性值決定的。

CSS規則

在CSS中最基本的單元就是box,所有的網頁本質上都是一堆box按照CSS規則和開發人員的設定形成的一個3D模型的平面效果圖。和人類有男女性別一樣,它們會分為塊級上下文和行級上下文。

行級上下文,英文名inline formatting context,表示這個區域內只能有inline-level box和line box,其他box來了還不接見,要是強行來了怎麼辦,網頁解析時把它扔到塊級上下文裡去,哈哈哈哈~~是不是夠霸氣!

舉個例子。

瀏覽網站時,我們大家看到的都是網頁解析完的樣子,還是剛才的這個網站

網頁文字的祕密

它背後的box平面圖是醬紫的

網頁文字的祕密
圖中的每個長方塊都是一個box。其中藍色區域對應的是網頁中的文章部分,第一塊藍色對應的是標題“New Post Title”,第二塊和第三塊分別對應第一段落和第二段落。每個紅色區域都是一個line box,每個紫色塊都是一個inline-level box。

不管是標題還是段落,每行文字都由一個line box包圍,line box預設是從上到下依次排列。每行中的每個單詞都由一個inline-level box包裹著,它們會依次擺放在一個line box中,一行擺滿,就會自動換到下一個line box中。

大家可能疑惑了,行級上下文呢?其實每塊藍色區域都會產生一個行級上下文,它是一個虛擬的,不會像box一樣有明顯的邊界。我們所看到的紅色區域和紫色塊都屬於這個行級上下文。

說了這麼多,總結一下規則吧

  • line box(即每行文字)在行級上下文中預設是從上到下一行行排下來,可通過設定屬性值達成
  • inline-level box(即每個單詞)在line box中擺放的順序預設是從左到右水平擺放,可通過設定屬性值達成

這些規則就決定了我們看到的文字都是整齊排列的。當然,如果我們堅持上下參差不齊的效果,這也是可以做到的,以後再分享給大家。

屬性值

在CSS中,有個屬性叫writing-mode。該屬性決定了line box之間在行級上下文中按照什麼方式排列,以及line box本身是水平擺放還是垂直襬放。

可以設定的屬性值有:

horizontal-tb | vertical-rl | vertical-lr | sideways-rl | sideways-lr
複製程式碼

如果沒有設定writing-mode,預設為horizontal-tb。那麼每個line box就會水平擺放,line box之間會從上(top)到下(bottom)依次擺放。就如同上面的box平面圖所示。

對於如下一個網頁

<html>
<head>
<style>
div {
    width: 600px;
    height: 160px;
    padding: 20px;
    line-height: 30px;
    text-indent: 30px;
    background-color: rgba(62, 174, 236, 0.78);
    color: white;
    }
</style>
</head>
<body>
    <div>
      An ancient Hebraic text says:" love is as strong as death". It seems that not everyone experiences this kind of strong love. The increasing probably,crime and war tells us that the world is in indispensable need of true love. But what is true love?Love is something we all need.But how do we know when we experience it?
    </div>
</body>
</html>複製程式碼

如果沒有設定writing-mode,則writing-mode為horizontal-tb,那麼它呈現的是

網頁文字的祕密

如果設定writing-mode為vertical-lr,網頁程式碼改為:

<html>
<head>
<style>
div {
    width: 600px;
    height: 160px;
    padding: 20px;
    line-height: 30px;
    text-indent: 30px;
    background-color: rgba(62, 174, 236, 0.78);
    color: white;
    writing-mode:vertical-lr;
    }
</style>
</head>
<body>
    <div>
      An ancient Hebraic text says:" love is as strong as death". It seems that not everyone experiences this kind of strong love. The increasing probably,crime and war tells us that the world is in indispensable need of true love. But what is true love?
Love is something we all need.But how do we know when we experience it?
      
    </div>
</body>
</html>
複製程式碼

它呈現的將是

網頁文字的祕密
可以看到,每個line box(每豎文字)垂直襬放,每個line box之間是從左到右依次排列。

按照正常的文字瀏覽習慣,文字均是水平的從左到右依次展開。今天把這些知識分享給大家,無非是想讓大家知道背後的原理。知道了原理,如果你想另類呈現文字就可以隨心所欲啦~

今天就講這麼多啦,下次再見!

ps: 本文例子均是在chrome上測試。


相關文章