How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?
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
最新文章
- C++ 实现Range类,用于常规遍历
- win环境变量立即生效
- PHP读取XML
- UDP发送数据测试
- ReportViewer技巧汇总
- 4.python函数基础
- 递归函数与fibonacci
- Spring Http Invoker
- post跨域请求
- 【转】Directx11 SDK文档
- 在代码中控制UI界面
- jenkins+ant+jmeter自动化环境搭建(一)
- SSIS 检查点
- Connection reset by peer的常见原因
- 使用scrapy选择器selector解析获取百度结果
- c/c++求解图的关键路径 critical path
- H5 68-伪元素选择器
- UGUI实现摇杆
- 删除node_modules文件
- Django(图书管理系统2)