1
votes

I have an image in a div inside of a container div. When I apply a margin-top to the image the margin gets applied outside of the container div (pushing the container) down in relation to the body.

I can "fix" this by applying a padding onto the other div... but I'd rather have a margin on my image. If I apply even a 1px padding onto the other (not container) div then the margin-top works as expected in pushing the image down.

CSS:

body {
    background: #bada44
}
.container {
    background: #776;
}
.other {
    background: #ccc;
    /*padding: 1px;*/
}
img {
    width: 33%;
    display: block;
    margin: 0 auto;
    margin-top: 30px;
}

HTML

<div class="container">
    <div class="other">
        <img src="something.jpg" />
    </div>
</div>

jsFiddle: http://jsfiddle.net/mguQY/1/

I'm using Chrome

2
Read my explanation at stackoverflow.com/a/15980020/1729885, margins collapse onto eachother.Niels Keurentjes

2 Answers

2
votes

Déjà vu :D Add overflow: hidden; to .other :

.other {
    background: #ccc;
    /*padding: 1px;*/
    overflow: hidden;
}

http://jsfiddle.net/mguQY/2/

1
votes

use padding-top instead of margin-top