Why does margin-top not work as expected? How to fix this?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jezternz
    New Member
    • Jan 2008
    • 145

    Why does margin-top not work as expected? How to fix this?

    Okay,
    So I have been working with HTML and CSS for a number of years, and recently I came across something I did not realize would happen.

    When you have a parent division (relative/static), and you have a child division with "margin-top:40px".

    What will happen is the parent division will actually be pushed down 40px from its parent and the child div will actually just sit on the top.

    What confuses me more is that this is not the case for margin-left and the left side???

    Is there any way I can make the child divisions margin occur between the child div and the parent div and not above.

    A live pastebin for HTML, CSS & JavaScript and a range of processors, including SCSS, CoffeeScript, Jade and more...


    ** I have noticed that adding a padding of 1px to the parent will make it work, however because of the way this is setup in my web application (JS), I unfortunately cannot add padding.

    Cheers, J
  • drhowarddrfine
    Recognized Expert Expert
    • Sep 2006
    • 7434

    #2
    This is called margin collapse and is defined in the spec. There are two ways around it. One is to place a border around the parent. The other I can't think of right now but I'm sure there's others, too.

    Comment

    • Jezternz
      New Member
      • Jan 2008
      • 145

      #3
      Thanks for the help.
      Did a bit more googling on "Margin Collapsing" and found the following seems to work:
      • display of the child is set to: inline-block
      • float of the child is set to: left/right
      • clear is not set to none.
      • zoom (transformation ) of the child is set.


      source

      Cheers, J

      Comment

      Working...