一、position的概念
作為布局必不可缺少的元素之一,深究其屬性以及一些注意點是非常必要的。
定義:規定元素的定位類型。
position屬性:
屬性 |
描述 |
常用性 |
absolute |
產生絕對位置的元素,相對於static定位以外的第一個父元素進行定位。 |
★★ |
relative |
產生相對定位的元素,相對於其在文檔流正常位置進行定位。 |
★★ |
fixed |
產生絕對位置的元素,相對於瀏覽器視窗進行定位。 |
★☆ |
static |
預設值。沒有定位,元素出現在正常的流中(忽略 top, bottom, left, right 或者 z-index 聲明) |
☆☆ |
從表格中可以瞭解到position的主要概念,有幾點需要注意:
二、position屬性的一些注意點1. absolute的定位問題
absolute所定位的位置是最近帶有position屬性並且屬性值不為static的父級元素。子項目預設定位在父元素的左上方位置。
如果子項目僅僅設定了position:absolute,而未設定left、top之類的元素。和對應的padding無關。
舉個例子:如果子項目設定了bottom:0;如果父元素存在padding:20px;那麼padding-bottom:20px;會失效,但是padding-left:20px;依然奏效。比如:
//cssdiv{ width:200px; height:200px;}.fatherDiv{ background-color:#12B7F5; position:relative; padding:20px; margin-top:20px;}.childDiv{ width:100px; height:100px; background-color:#F9b041; position:absolute; bottom:0px;}//html<div class="fatherDiv"> <div class="childDiv"></div></div>
當然如果你既設定了left、又設定了bottom.那麼父元素的padding的任何設定是對子項目產生不了任何影響
這裡需要注意,margin無論什麼值都也都會影響到子項目,因為它是直接影響父級。
2. relative的定位問題
以下例子都以下面為基礎樣式
//cssdiv{ width:200px; height:200px;}.brotherDiv{ background-color:#12B7F5;}.brotherDiv1{ background-color:#F9b041;}//html<div class="brotherDiv"></div><div class="brotherDiv1"></div>
i. 兩個div為塊級(block)元素
兩者的left、top....都不會相互影響.因為即使元素位置改變了,但是它在文檔流佔用的空間不變,所以並不會影響到布局。
.brotherDiv{ position:relative; top:40px;}.brotherDiv1{ position: relative;}
另外還可以通過z-index設定顯示的層次。例如給brotherDiv設定z-index:1,則藍色塊會覆蓋黃色(z-index預設為0)
ii. 兩個div為行內-塊級(inline-block)元素
除了同樣擁有第一個特性以外,還多了一個特有的特性:
margin和padding都會影響到同行元素
.brotherDiv{ position:relative; display: inline-block; margin-top:40px;}.brotherDiv1{ background-color:#F9b041; position:relative; display: inline-block;}
我們看一下兩個div的style面板
發現brotherDiv1並不存在margin.
我們用JS擷取一下兩個margin:
window.onload = function(){ var div = document.querySelector('.brotherDiv'); var div1 = document.querySelector('.brotherDiv1'); console.log(div.offsetTop); //40 console.log(div1.offsetTop); //40}
用js的話是可以擷取兩者的位移量的,也就是說brotherDiv1實際上也位移了。
而用padding的情況就比較常見.兩個元素預設會底部對齊。並且高度低的元素會獲得位移量
//css.brotherDiv{ background-color:#12B7F5; position:relative; display: inline-block; padding:20px;}.brotherDiv1{ background-color:#F9b041; display: inline-block; position:relative;}//html<div class="brotherDiv"></div><div class="brotherDiv1"></div>//jswindow.onload = function(){ var div = document.querySelector('.brotherDiv'); var div1 = document.querySelector('.brotherDiv1'); console.log(div.offsetTop); //0 console.log(div1.offsetTop); //40}
當然,對齊的方法相信大家都非常熟悉了。
在高低較低的元素設定css
//把元素的頂端與行中最高元素的頂端對齊vertical: top;//把此元素放置在父元素的中部vertical: middle;// 把元素的頂端與行中最低的元素的頂端對齊vertical: bottom;
注意,這裡的middle並非是相對行內元素置中的意思。
感興趣的可以看看這篇文章:《HTML元素垂直置中的n種方法》