CSS篇02--margin和padding


一、margin

1.负 margin 位移自己:demo

2.负 margin-right/margin-bottom 位移别人:demo

3.负 margin 扩大面积:经常用来解决 inline-block li 的 margin 超出父容器的问题;

4.margin collapse(margin 合并)
本节参考自知乎作者貘吃馍香
链接:http://www.zhihu.com/question/24563593/answer/28254084

w3c collapsing margins
基本上这节意思是说,比邻元素的边距总是折叠。
但是得除了以下几种情况:

Margins of the root element’s box do not collapse.(根元素不折叠)
If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.(有间隙不折叠)

Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children). (浮动不折叠)
Margins of elements that establish new block formatting contexts (such as floats and elements with ‘overflow’ other than ‘visible’) do not collapse with their in-flow children.(创建 BFC 与子不折叠)
Margins of absolutely positioned boxes do not collapse (not even with their in-flow children).(positioned 不折叠)
Margins of inline-block boxes do not collapse (not even with their in-flow children).(inline-box 不折叠)
The bottom margin of an in-flow block-level element always collapses with the top margin of its next in-flow block-level sibling, unless that sibling has clearance.(兄弟有间隙不折叠)
The top margin of an in-flow block element collapses with its first in-flow block-level child’s top margin if the element has no top border, no top padding, and the child has no clearance.(父子间有 padding 和 border 不折叠)

5.margin 居中:margin-left: auto; margin-right: auto;

6.注意 margin-top 值为百分比时也以 width 为基准。

二、padding

1.negative value are not allowed; 2.利用 padding 来保持高宽比:图片保持比例超出隐藏图片保持比例缩放
3.padding 与绝对定位:如果 parent 设定了 margin,border,padding 等属性,那么这个定位点将忽略 padding,将会从 padding 开始的地方(即只从 padding 的左上角开始)进行定位。demo;
4.padding 补偿法:利用超大内边距和相同的负外边距实现三列等高。优点是比较简单,纯 css 实现,缺点是无法看到下边,需再套一层 div。


文章作者: Angus
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Angus !
  目录