網頁文字的祕密

你們知道爲何90%的網站上的文字都是從左到右整齊的排列着,像這樣
html

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

其實這是由CSS自己的規則以及前端開發人員設定的屬性值決定的。

CSS規則

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

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

舉個栗子。ide

瀏覽網站時,咱們你們看到的都是網頁解析完的樣子,仍是剛纔的這個網站測試

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

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

無論是標題仍是段落,每行文字都由一個line box包圍,line box默認是從上到下依次排列。每行中的每一個單詞都由一個inline-level box包裹着,它們會依次擺放在一個line box中,一行擺滿,就會自動換到下一個line box中。ui

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

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

  • 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上測試。

相關文章
相關標籤/搜索