开发者

CSS - Negative Margin To Remove Parent's Padding

开发者 https://www.devze.com 2023-01-26 18:55 出处:网络
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?

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>


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.


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


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消