网页文字的秘密

你们知道为何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上测试。

相关文章
相关标签/搜索