margin百分比,重叠和auto
一. margin百分比
1. 普通元素的百分比margin都是相對于容器的寬度計算
2. 絕對定位元素的百分比margin是相對于第一個定位祖先元素(relative/absolute/fixed)的寬度計算
這是在默認的 writing-mode: horizontal-tb; 和 direction: ltr; 的情況下,
若書寫模式變成縱向的時候,其參照將會變成包含塊的高度。
二. margin重疊
1. 通常特性
block水平元素(不包括float和absolute元素)
不考慮writing-mode,只發生在垂直方向(margin-top/margin-bottom)
2. 重疊的3種情境
A.相鄰的兄弟元素
B. 父級和第一個/最后一個子元素
子元素的margin-top相當于父元素的margin-top
a.margin-top重疊
父元素非塊狀格式化上下文元素
父元素沒有border-top設置
父元素沒有padding-top值
父元素和第一個子元素之間沒有inline元素分隔
b.margin-bottom重疊
父元素非塊狀格式化上下文設置
父元素沒有border-bottom設置
父元素沒有padding-bottom值
父元素和第一個子元素之間沒有inline元素分隔
父元素沒有height,min-height,max-height
C.空的block元素
元素沒有border設置
元素沒有padding值
里面沒有inline元素
沒有height或者min-height
3. 計算規則
正正取大值
正負值相加
負負最負值
4. margin重疊的解決方法
4.1 相鄰兄弟元素的重疊
最簡單的方法是,使用同方向的margin,即A盒子margin-bottom: 50px,B盒子margin-top: 100px,直接用B盒子margin:150px就行了,不用使用兩個方向的margin。
4.2 父子元素的重疊
4.2.1? 給父元素添加一個before偽元素,.father:bofore{content:' ';display:table;},content中有個空格
4.2.2 將父元素做成BFC,例如overflow:hidden
4.2.3 對父元素使用padding-top,不使用margin
4.2.4 將父元素定位,例如,position:fixed
三. margin auto
margin的值為auto,是自動占據包含塊的剩余空間,例如
<div id="demo"><p>恩,我就是那個p。</p> </div> #demo{width: 500px; } #demo p{width: 100px;margin-left: auto; }則p的實際margin-left為500-100=400px,p元素右對齊
當margin-left和margin-right同為auto時,左右平分剩余空間,元素居中
?
?
參考:https://segmentfault.com/a/1190000006212076
? ? ? ? ?http://www.ituring.com.cn/article/64580
? ? ? ? ?http://www.ituring.com.cn/article/64581? https://blog.csdn.net/shi_1204/article/details/80180224
? ? ? ? ?https://tech.youzan.com/css-margin-collapse/
轉載于:https://www.cnblogs.com/mengff/p/6083058.html
總結
以上是生活随笔為你收集整理的margin百分比,重叠和auto的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QT中生成字符串md5的方法
- 下一篇: 6-2-1:STL之string——st