Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

html - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...