可能大家都用會 margin
或者相對偏移的 top, right, bottom, left
來做一些類似元素偏移的事,其實我也會。這回我們只聊 relative
下的 top, right, bottom, left
。
比如說我們想讓一個 div 向下偏移 50 個像素,通常會這樣:
#demo .margin-top{
margin-top: 50px;
}
#demo .relative-top{
position:relative;
top: 50px;
}
<div id="demo">
<div class="margin-top">我是margin-top:50px</div>
<div class="relative-top">我是relative top:50px</div>
</div>
上述2種方式,我們都可以完成 div 向下偏移 50 個像素的需求。來看看 DEMO1
: margin-top vs. relative top
從上面的例子,可以發(fā)現(xiàn)不論是 margin-top
還是 relative top
都是以自身作為參照物進行偏移的。
順帶說一下 absolute
偏移相對的是包含塊,并且其偏移值是從包含塊的 padding
區(qū)域開始計算。
原文:Margins in CSS serve to add both horizontal and vertical space between boxes.
翻譯:CSS中的margin用來添加盒子之間的水平和垂直間隙。
原文:An element is said to be positioned if its ‘position’ property has a value other than ‘static’. Positioned elements generate positioned boxes, and may be laid out according to the following four physical properties: top, right, bottom, left.
翻譯:一個元素的position屬性值如果不為static則發(fā)生定位。定位元素會產(chǎn)生定位盒,并且會根據(jù) top, right, bottom, left 這4個物理屬性進行排版布局。
意思很明白,margin
是用來增加自身與它人之間的空白,而 top, right, bottom, left
是用來對自身進行排版,作用完全不同。
也就是說 margin
是互動的,因為它要影響它人;而 top, right, bottom, left
是孤獨的,它只是自己一個人玩,不影響它人。
在 DEMO1
中,我們看到2個方法都可以做到向下偏移50px,不過它們的意義不太一樣。
margin的case: 讓該div的頂部與其相鄰的元素(這里即其包含塊)留有50px的空白。
top的case: 讓該div距離其包含塊頂部邊緣50px,因為是 relative ,所以這里是距離div自己的頂部邊緣。
如果我們設(shè)置 margin-bottom
和 bottom
的值也為50px,它們的表現(xiàn)將完全不一樣,你覺得呢? 恩,試試:
#demo .margin-bottom{
margin-bottom: 50px;
}
#demo .relative-bottom{
position: relative;
bottom: 50px;
}
<div id="demo">
<p class="margin-bottom">我是margin-bottom:50px</p>
<p class="relative-bottom">我是relative bottom:50px</p>
</div>
驗證猜想的時刻到了,來看看 DEMO2
: 對margin-bottom和bottom的表現(xiàn)猜想
結(jié)果有出乎你的意料嗎?好吧,不論怎么,解釋下為什么會這樣?
前面我們說過 margin
是用來增加自身與它人之間的間隙,所以它距包含塊底部有50px,這應該能理解?那為什么 bottom
會跑到上面去?相信仔細看了之前的描述,你應該知道。因為它要相對自己的底部邊緣有50px,恩,不是-50px,所以它等于是向上偏移了50px,很簡單,不是嗎?
還有一個細節(jié)你注意到了嗎?bottom
沒有撐開它的包含塊,仔細看看它的包含塊的背景色區(qū)域。這正好也驗證了之前說的 top, right, bottom, left
是孤獨的,它只是自己一個人玩,不影響它人。
孤獨患者
我們將 DEMO1
稍改改,為其加上一點上下文,再看看結(jié)果:
#demo .margin-top p{
margin-top: 50px;
}
#demo .relative-top p{
position:relative;
top: 50px;
}
```html:
我是margin-top:50px
我是一段隨便什么上下文我是relative top:50px
我是一段隨便什么上下文
迫不及待的要看看實際例子了,不是么?`DEMO3`: [再次驗證一下top, right, bottom, left是孤獨患者](http://demo.doyoe.com/css/margin/margin-top-vs-relative-top-2.htm)
至此可以再次說明 `top, right, bottom, left` 真的和其上下文一毛錢關(guān)系都沒有,絕對的孤單患者。
所以 `margin 和 top, right, bottom, left` 分別要在什么場景使用,應該可以有考量的依據(jù)了,不是么?enjoy it.
## 似乎還漏了點啥
差點就這么結(jié)篇了,想起還有點遺漏的地方。
當position為relative時,如果top和bottom都是auto,則它們的計算值是0,right和left亦然;如果top和bottom其中一個為auto,則auto相當于另一個的負值,即top = -bottom,right和left亦然;如果top和bottom的值都不為auto,則忽略bottom,如果right和left的值都不為auto,則忽略right。
好吧,不得不再寫個例子:`DEMO4`: [top, right, bottom, left詳述](http://demo.doyoe.com/css/margin/top-right-bottom-left.htm)
至于margin,就留給大家思考一下也不錯 ^_^
enjoy it again.
## 可參考:
- http://dev.w3.org/csswg/css-box/#the-margin-properties
- http://dev.w3.org/csswg/css-position/#box-offsets-trbl
更多建議: