3

I have a div that contains a link:

<div id="like_bar"><a href="#" onclick="return false;" id="like"></a></div>

With some CSS:

#like_bar{
    width:140px;
    height:26px;
    background:url('bar.jpg');
}
#like{
    display:block;
    width:20px;
    height:20px;
    margin:3px 36px;
    background:url('mini_img.png');
}

The link is placed at the top of the bar and the margins on the link are applied to the bar.
This is annoying.


Could someone explain these collapsing margins, how to avoid them and what they're used for.
Web_Designer
  • 72,308
  • 93
  • 206
  • 262

2 Answers2

3

There are many ways to "fix this".

Perhaps the easiest for you would be this:

#like_bar {
    overflow: hidden
}

Other ways include:

  • Add some padding
  • Add a border (even border: 1px solid transparent is enough)
  • float the element
  • position: absolute
  • And, like in the snippet above, set overflow to a value other than the default of visible.

You also asked:

what they're used for

A common use case is the <p> tag.

See: http://jsfiddle.net/thirtydot/tPaTY/

Without margin collapsing, certain things would become annoying.

thirtydot
  • 224,678
  • 48
  • 389
  • 349
1

Because I'm lazy I'm just going to link to a few resources:

My answer here explains why the box model is the way it is, which is related to margin-collapsing being included.

The w3c css spec defines the behavior of margin collapsing. It's an expected behavior for convenience given the box model. You don't need to worry about double margins between blocks of content with it. What it sounds like you actually want is some padding around #like, rather than margins.

Think of CSS as a content-centric inside→out approach to styling, rather than a programmed outside→in approach.

Community
  • 1
  • 1
zzzzBov
  • 174,988
  • 54
  • 320
  • 367