CSS 入门教程(5):静态位置、相对位置、绝对位置
    
  
      
      
     
    
      
        position 属性指定元素使用的定位方法类型(静态、相对、固定、绝对或粘性)。
position CSS 属性设置元素在文档中的定位方式。top、right、bottom 和 left 属性确定定位元素的最终位置。
- 
position: static;
元素根据文档的正常流程定位。top、right、bottom、left 和 z-index 属性不起作用。这是默认值。
 
- 
position:relative;
元素根据文档的正常流程定位,然后根据 top、right、bottom 和 left 的值相对于自身偏移。偏移不会影响任何其他元素的位置;因此,页面布局中为元素提供的空间与位置为静态时相同。
 
- 
position:absolute;
元素从正常文档流中移除,并且不会在页面布局中为元素创建任何空间。它相对于其最近的定位祖先(如果有)进行定位;否则,它相对于初始包含块进行定位。其最终位置由顶部、右侧、底部和左侧的值决定。
 
- 
position: fixed;
类似于 position: absolute 但相对位置停留在视口而不是页面(如绝对位置)。
 
让我们创建一个示例。创建以下元素:
1 2 3 4 5
   | <body>     <div>BOX 1</div>     <h1>position: static;</h1>     <div>BOX 2</div> </body>
   | 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   | div {     color: lighgray;     font-size: 20px;     background-color: darkgray;     border: solid gray;     padding: 10px;     height: 40px;     margin: 10px; }
  h1 {     background-color: red;     margin: 10px;     padding: 10px;     font-size: 20px;     border: solid;     position: static;     left: 20px;     top: 10px; }
  | 
 
静态(忽略左侧和顶部):

相对定位
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   | div {     color: lighgray;     font-size: 20px;     background-color: darkgray;     border: solid gray;     padding: 10px;     height: 40px;     margin: 10px; }
  h1 {     background-color: red;     margin: 10px;     padding: 10px;     font-size: 20px;     border: solid;     position: relative;     left: 20px;     top: 10px; }
  | 
 
相对(元素位置距原始位置左侧 20px 和顶部 10px)

绝对定位
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   | div {     color: lighgray;     font-size: 20px;     background-color: darkgray;     border: solid gray;     padding: 10px;     height: 40px;     margin: 10px; }
  h1 {     background-color: red;     margin: 10px;     padding: 10px;     font-size: 20px;     border: solid;     position: absolute;     left: 20px;     top: 10px; }
  | 
 
绝对(元素位置距页面左侧 20px 和顶部 10px)

相关文章:
      
     
    
      
  
  
    
      
      
        
        致力于网站建设与Web开发。喜欢新事物,关注前后端动态,对新的技术有追求, 做一个优秀的web全栈工程师。