在CSS中一共有N種定位方式,其中,static ,relative,absolute三種方式是最基本最常用的三種定位方式。他們的基
本介紹如下。
static預設定位方式
relative相對定位,相對於原來的位置,但是原來的位置仍然保留
absolute定位,相對於最近的非標準劉定位,原來的位置消失,被後邊的位置所頂替
下面先示範相對定位的案例
<!DOCTYPE html><html> <head> <title>relative.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../css/relative.css" type="text/css"></link> </head> <body> <div class="style1">內容一</div> <div id="special" class="style1">內容二</div> <div class="style1">內容三</div> <div class="style1">內容四</div> </body></html>
CSS代碼如下
.style1{width: 300px;height: 100px;background-color: gray;border: 1px solid red;float: left;margin-left: 10px;}#special{position: relative;/*這裡使用了相對定位,left意思是在原來的位置向左移動多少*/left: 40px;/*左側座標變大,向右移動*/top: 200px;}
其中的left是值擴大left的長度,也就是向右移動,當然了,是相對於這個模組的原來的位置。他的後面的元素不會頂
替他的位置,效果圖
然後是絕對位置。其中,HTML代碼不變,至改變了CSS代碼
.style1{width: 300px;height: 100px;background-color: gray;border: 1px solid red;float: left;margin-left: 10px;}#special{position: absolute;/*這裡使用了相對定位,left意思是在原來的位置向左移動多少*/left: 40px;/*左側座標變大,向右移動*/top: 200px;}
絕對位置這裡就是相對於body這個元素的絕對位置,當然了,當他的最近處有一個非標準流的東西,他就會跟那個非
標準流為標準進行配對。
效果如如下