CSS - 负边距删除父级的填充
使用负边距来删除包装元素的填充是一个好习惯吗?
例如,使用以下哪一个代码片段更好?
<div style="padding: 5px;">
Shortened width string
<div style="margin: 0 -5px;">Full width string</div>
Shortened width string
</div>
或者
<div>
<div style="padding: 5px;">Shortened width string</div>
<div>Full width string</div>
<div style="padding: 5px;">Shortened width string</div>
</div>
Is it a good practise to use negative margins to remove padding of wrapper element?
For example, which of the following code pieces is better to use?
<div style="padding: 5px;">
Shortened width string
<div style="margin: 0 -5px;">Full width string</div>
Shortened width string
</div>
or
<div>
<div style="padding: 5px;">Shortened width string</div>
<div>Full width string</div>
<div style="padding: 5px;">Shortened width string</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不直接声明
padding:5px 0;
这样就没有水平填充呢?尽管我认为使用负边距是完全可以的,但这就是它们的用途,但如果您可以首先避免它们,那就这样做。Why not just declare
padding:5px 0;
so you don't have horizontal padding? Though I would argue that it's perfectly fine to use negative margins, that's what they're made for but if you can avoid them in the first place, do so.好吧,这几乎就是一个黑客。只要有节制地使用,我会说没问题。关键是要确保它易于阅读和理解。如果需要,请添加评论。
Well it's bordering on being a hack. As long as it's used with restraint thpugh, I would say it's ok. The key is to make sure it's easy to read and understand. Add comments if you need to.
第二个要优越得多。应避免负边距,因为它们会导致 IE 出现问题。
The second is far superior. Negative margins should be avoided because they will cause you problems in IE.
负边距隐藏了div……这是技巧
使用缩放:1,位置:相对
这是示例
问题:
在工具栏div的IE红色区域中隐藏自身。即使我们使用 Zoom: 1。为了解决这个问题,我们也需要添加position:relative。
解决方案:
所以你的css类将变成
negative margin its hide the div…. Here is trick
use zoom:1, position: relative
Here is Example
Problem:
in IE red area of toolbar div hide itself. even we are using zoom: 1. to get rid of this problem we need to add position: relative too.
Solution:
so your css class will become