先看如下代码:
- <body style="margin:0px;padding:0px;">
- <div style="background-color:#FF0000;">
- <div style="margin:10px;background-color:#00FF00;">cftea</div>
- </div>
- </body>
这段代码在各浏览器中的表现结果均相同,下图是从 Chrome 中的截图表现:
这说明:margin-top 是相对于 body 的,而 margin-left 是相对于外层 div 的。这里说相对于 body 可能不准确,比如在最外层再套一个 table,它就是相对 table 的 td 的了。
现在再看看另一段代码:
- <body style="margin:0px;padding:0px;">
- <div style="width:100px;background-color:#FF0000;">
- <div style="margin:10px;background-color:#00FF00;">cftea</div>
- </div>
- </body>
为外层 div 增加了 width,在 Firefox 中效果不变,在 IE 中变成了这样的:
这说明指定外层 div 的 width 后,在 IE 中,内层 div 的 margin-top 就是相对外层 div 的了。
最后再看看另一段代码:
- <body style="margin:0px;padding:0px;">
- <div style="position:absolute;background-color:#FF0000;">
- <div style="margin:10px;background-color:#00FF00;">cftea</div>
- </div>
- </body>
把 width:100% 改为 position:absolute,这时,各浏览器中的表现结果均相同,内层 div 的 margin-top、margin-left 均是相对外层 div,并且外层 div 的宽度不再是 100%,而是紧缩到贴近内层 div 的 margin 边缘。
欢迎大家阅读《margin-top 与 margin-left 不仅是方向…_css》,跪求各位点评,若觉得好的话请收藏本文,by 搞代码