How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

解答

 

Negative margins are valid in css and understanding their (compliant) behaviour is mainly based on the box model and margin collapsing. While certain scenarios are more complex, a lot of common mistakes can be avoided after studying the spec.

For instance, rendering of your sample code is guided by the css spec as described in calculating heights and margins for absolutely positioned non-replaced elements.

If I were to make a graphical representation, I'd probably go with something like this (not to scale):

The margin box lost 8px on the top, however this does not affect the content & padding boxes. Because your element is absolutely positioned, moving the element 8px up does not cause any further disturbance to the layout; with static in-flow content that's not always the case.

Bonus:

Still need convincing that reading specs is the way to go (as opposed to articles like this)? I see you're trying to vertically center the element, so why do you have to set margin-top:-8px; and not margin-top:-50%;?

Well, vertical centering in CSS is harder than it should be. When setting even top or bottom margins in %, the value is calculated as a percentage always relative to the width of the containing block. This is rather a common pitfall and the quirk is rarely described outside of w3 docos

最新文章

  1. C++ 实现Range类,用于常规遍历
  2. win环境变量立即生效
  3. PHP读取XML
  4. UDP发送数据测试
  5. ReportViewer技巧汇总
  6. 4.python函数基础
  7. 递归函数与fibonacci
  8. Spring Http Invoker
  9. post跨域请求
  10. 【转】Directx11 SDK文档
  11. 在代码中控制UI界面
  12. jenkins+ant+jmeter自动化环境搭建(一)
  13. SSIS 检查点
  14. Connection reset by peer的常见原因
  15. 使用scrapy选择器selector解析获取百度结果
  16. c/c++求解图的关键路径 critical path
  17. H5 68-伪元素选择器
  18. UGUI实现摇杆
  19. 删除node_modules文件
  20. Django(图书管理系统2)

热门文章

  1. 6.Redis的事务
  2. redis集群1
  3. Flutter——Wrap组件(流式布局)
  4. python获取字符串的前几个字符(包含汉字)
  5. xargs 使用详解
  6. 【Java 基础实验_Bank项目_06】单例模式(Static Bank) , 查询异常输出
  7. ArcGIS10.6 通过ArcMap发布二维数据服务。
  8. 0005SpringBoot中用Junit测试实体类中绑定yml中的值
  9. linux学习-添加多个硬盘和lvm配置
  10. PL/SQL老是自动断开问题处理