CSS - 负边距删除父级的填充

发布于 2024-10-03 19:56:20 字数 485 浏览 10 评论 0原文

使用负边距来删除包装元素的填充是一个好习惯吗?

例如,使用以下哪一个代码片段更好?

<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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

潜移默化 2024-10-10 19:56:20

为什么不直接声明 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.

暖风昔人 2024-10-10 19:56:20

好吧,这几乎就是一个黑客。只要有节制地使用,我会说没问题。关键是要确保它易于阅读和理解。如果需要,请添加评论。

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.

岛徒 2024-10-10 19:56:20

第二个要优越得多。应避免负边距,因为它们会导致 IE 出现问题。

The second is far superior. Negative margins should be avoided because they will cause you problems in IE.

小伙你站住 2024-10-10 19:56:20

负边距隐藏了div……这是技巧
使用缩放:1,位置:相对

这是示例

问题:

.container{
padding: 20px;
}
.toolbar{
margin-top: -10px ;
}

在工具栏div的IE红色区域中隐藏自身。即使我们使用 Zoom: 1。为了解决这个问题,我们也需要添加position:relative。

解决方案:

所以你的css类将变成

.container{
padding: 20px;
}
.toolbar{
margin-top: -10px ;
zoom: 1;
position: relative;
}

negative margin its hide the div…. Here is trick
use zoom:1, position: relative

Here is Example

Problem:

.container{
padding: 20px;
}
.toolbar{
margin-top: -10px ;
}

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

.container{
padding: 20px;
}
.toolbar{
margin-top: -10px ;
zoom: 1;
position: relative;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文