css中定位問題:絕對位置、相對定位、fixed和static

來源:互聯網
上載者:User
本篇文章給大家帶來的內容是關於css中定位問題:絕對位置、相對定位、fixed和static,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。

1.絕對位置(absolute):脫離原來位置進行定位,可以使用left right top bottom進行定位

html代碼

<!DOCTYPE html><html lang="en"><head><meter charset="utf-8"><title>hhhh</title> <link rel="stylesheet" type="text/css" href="lesson3.css"></head><body><p class="demo"></p><p class="box"></p></body></html>

css代碼:

*{margin:0;padding:0;}.demo{position:absolute; /*top:100px;left:100px;*/width: 100px;height: 100px;background-color: red;opacity: 0.5;     /*透明度*/}.box{width:150px;height:150px;background-color: green;}

沒有使用opsition定位時效果(p元素是區塊層級元素,獨佔一行)

加上定位,沒有設定top left 時效果(此時demo和box不在同一層面)

加上top left效果

2.相對定位(relative):保留原來位置進行定位,可以使用left right top bottom進行定位

html代碼:

<!DOCTYPE html><html lang="en"><head><meter charset="utf-8"><title>hhhh</title> <link rel="stylesheet" type="text/css" href="lesson3.css"></head><body><p class="demo"></p><p class="box"></p></body></html>

css代碼

*{margin:0;padding:0;}.demo{position:relative; /*top:100px;left:100px;*/width: 100px;height: 100px;background-color: red;opacity: 0.5;     /*透明度*/}.box{width:150px;height:150px;background-color: green;}

沒有使用opsition定位時

使用opsition定位 不加top left 時

使用opsition定位 加上top left 時(保留紅色原來的位置進行定位,上方有空出原來紅色的部分)

3.fixed:相對於瀏覽器的視窗對元素進行定位,可以使用left right top bottom進行定位

4.static:預設值,沒有定位,top left 等不起作用

注意:存在父子項目使用定位時

absolute: 相對於最近的有定位的父級進行定位,要是沒有最就相對文檔進行定位
relative:相對於自己原來的位置進行定位

通常情況下,我們使用relative作為參照物,使用absolute進行定位

例如:

<div class="wrapper">    <div class="demo">            <div class="box"></div>    </div></div>

若使box參照demo進行定位則

*{margin:0;padding:0;}.wrapper{margin-left: 100px;width: 200px;height: 200px;background-color: orange;}.demo{position:relative; margin-left: 100px;width: 100px;height: 100px;background-color: red;}.box{position:absolute;left: 50px;width:50px;height:50px;background-color: green;}
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.