When I try to shift the image upwards using negative margin the whole container is moved upwards

So, here is the html code:

<div class="bottom_block">
   <a class="logo" href="#">
    <img src="img/logo_uniqa.jpg" height="90px" width="100px" alt="logo">
   </a>
</div>

And here is css:

.bottom_block {
    background-color:  blue;
    height: 50px;
    width: 100%;

}
.logo {
    display:block;
    padding-bottom: 10px;

}
.logo img {
    display: block;
    margin:0 auto;
}

So, I used margin-top:-10px but it moves whole container, not only image.


Solution 1:

It is due to the margin-collapsing rule. To fix it, you can simply use a transparent border on the element:

.logo img {
   border: 1px solid transparent;
   margin-top: -10px;
   display: block;
}

What is margin collapsing?

I already linked to the documentation page of MDN for what margin collapsing is. Here's the quick look:

enter image description here

enter image description here

Now, why adding border aborts the margin-collapsing rule?

This is not the only way prevent margin-collapsing; there are other ways too such as adding padding to the element.

Why does this prevent collapsing of margin? Because it (the element) is separated from the box layout. I mean to say that the padding or border doesn't separate the element physically from one another, but margin separates each physically.

Okay, lets discuss how border, padding, or overflow techniques prevent a collapsing margin. To clear up things to you, I have made this picture of magnets. You may know the rule of opposite pole magnets if one is shifted the other would also shift instead of stitching with one-another.

Look at the pictures to know how margin collapse is prevented:

enter image description here

enter image description here

The rule of margin collapsing may not be exactly as the opposite pole of magnet rules. But to clear things up this is just enough I hope.