Top Margin Stolen From Child Element And Added to Parent (Margin Collapsing)

One of the biggest frustrations that I have encountered with my time dealing with CSS is the Collapsing Margin Bug.  It technically isn\'t a bug, because for some reason, this was actually intentional, but here it goes:

The Issue:
For this example, imagine that you have a child element (layer, paragraph text, heading, etc...) contained within a parent layer.  I often times want to adjust the how much room is above my child element, so I add the specification of  "margin-top: 5px;" to the style of the child element to add the necessary space above the element.  If you think that sounds logical, you\'d be wrong (at least in the convoluted world of CSS)!  The 5 pixel margin is taken from top of the child element and added to the top of the parent layer.  Makes complete sense...right.

The impacts of this can wreak havoc with a layout.  Generally, I expect that nested elements shouldn\'t affect the appearance of the page around it.  Because this will steal the margin from a child and apply it to the parent, any elements that then rely on the height of the parent layer, will then also break the layout, leading to white gaps, misaligned layers, etc...

The Solution:
The easiest solution is to just use padding, which I guess isn\'t subject to this issue.  Placing a "padding-top: 5px;" in the style of child layer should give the desired result.  This can of course lead to issues if there is a background image or color in the child element that you don\'t want above the text, but so far this is the best solution, amongst a list of solutions that are far from perfect (The perfect solution would be to fix the issue in the CSS specification).




Related Posts


Fixed Position Div Isn't Staying Fixed When Scrolling on Android

My nice fixed position toolbar wasn't sticking as it should as I scrolled through on my mobile browser window...
Read Post

Simple Sticky Element

The user scrolls down the page and once the scrolling reaches the top of an element of my choosing, that element sticks to the top of the window, so it's always visible from that point on...
Read Post

Chrome displays a different height than what Chrome says the height should be.

I was changing the height of an element, but no matter where I specified the height, it wasn't displaying what I was putting in
Read Post

A Nicer Select Dropdown

Better select boxes are all over the internet, but I actually couldn't find one that I liked, and that worked for what I needed...
Read Post