一、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;依然奏效。比如:
//css
div{
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的定位問題
以下例子都以下面為基礎樣式
//css
div{
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>
//js
window.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種方法》