关于CSS position,来自MDN的描述:
CSS position属性用于指定一个元素在文档中的定位方式。top、right、bottom、left 属性则决定了该元素的最终位置。
然后来看看什么是文档流(normal flow),下面是 www.w3.org 的描述:
Normal flow
Boxes in the normal flow belong to a formatting context, which may be block or inline, but not both simultaneously. Block-level boxes participate in a block formatting context. Inline-level boxes participate in an inline formatting context.
- normal flow直译为常规流、正常流,国内不知何原因大多译为文档流;
- 窗体自上而下分成一行一行,并在每行中按从左至右的顺序排放元素;
- 每个非浮动块级元素都独占一行, 浮动元素则按规定浮在行的一端,若当前行容不下,则另起新行再浮动;
- 内联元素也不会独占一行,几乎所有元素(包括块级,内联和列表元素)均可生成子行,用于摆放子元素;
- 有三种情况将使得元素脱离normal flow而存在,分别是 float,absolute ,fixed,但是在IE6中浮动元素也存在于normal flow中。
一、position: static
MDN的描述:
该关键字指定元素使用正常的布局行为,即元素在文档常规流中当前的布局位置。此时 top、right、bottom、left 属性无效。
个人补充:static是position的默认值。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>CSS-position-static</title> 6 <link rel="stylesheet" href="https://cdn.bootcss.com/normalize/8.0.0/normalize.css"> 7 <style> 8 .container{ 9 background-color: #868686; 10 width: 100%; 11 height: 300px; 12 } 13 .content{ 14 background-color: yellow; 15 width: 100px; 16 height: 100px; 17 position: static; 18 left: 10px;/* 这个left没有起作用 */ 19 } 20 </style> 21 </head> 22 <body> 23 <div class="container"> 24 <div class="content"> 25 </div> 26 </div> 27 </body> 28 </html>
对 content 的 position 设定 static 后,left就失效了,而元素(content)就以正常的 normal flow 形式呈现。
二、position: relative
MDN的描述:
该关键字下,元素先放置在未添加定位时的位置,再在不改变页面布局的前提下调整元素位置(因此会在此元素未添加定位时所在位置留下空白)。position:relative 对 table-*-group, table-row, table-column, table-cell, table-caption 元素无效。
个人理解:相对于normal flow中的原位置来定位。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>CSS-position-relative</title> 8 <link rel="stylesheet" href="https://cdn.bootcss.com/normalize/8.0.0/normalize.css"> 9 <style> 10 .container{ 11 background-color: #868686; 12 width: 100%; 13 height: 300px; 14 } 15 .content_0{ 16 background-color: yellow; 17 width: 100px; 18 height: 100px; 19 } 20 .content_1{ 21 background-color: red; 22 width: 100px; 23 height: 100px; 24 position: relative;/* 这里使用了relative */ 25 } 26 .content_2{ 27 background-color: black; 28 width: 100px; 29 height: 100px; 30 } 31 </style> 32 </head> 33 <body> 34 <div class="container"> 35 <div class="content_0"> 36 </div> 37 <div class="content_1"> 38 </div> 39 <div class="content_2"> 40 </div> 41 </div> 42 </body> 43 </html>
这是没有设置left、top等属性时,正常出现在normal flow