Denis Bobrovnikov
Denis Bobrovnikov

Reputation: 630

CSS - Negative Margin To Remove Parent's Padding

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>

Upvotes: 5

Views: 8637

Answers (4)

Abdul Wahid
Abdul Wahid

Reputation: 167

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

Upvotes: 0

mmurch
mmurch

Reputation: 463

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

Upvotes: 0

meder omuraliev
meder omuraliev

Reputation: 186562

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.

Upvotes: 2

Nathan
Nathan

Reputation: 11149

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.

Upvotes: 0

Related Questions