且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当我尝试使用负边距向上移动图像时,整个容器向上移动

更新时间:2022-12-26 17:40:11

这是由于





现在,为什么添加border会中止margin-collapsing规则?



这不是防止利差崩溃的唯一方法;还有其他方法,如添加填充到元素。



为什么这会防止折叠边距?因为它(元素)与框布局分离。我的意思是说,填充或边框不会使元素在物理上彼此分离,但是边缘在物理上分开。



好,让我们讨论边框,填充或溢出技术如何防止折叠边距。为了清理你的东西,我把这张磁铁的图片。你可能知道对极磁铁的规则,如果一个被移动,另一个也将移动,而不是互相缝合。



看看图片,知道如何边缘崩溃







边缘塌陷规则可能与磁铁规则的相反极性不完全相同。但是要清除这些,这只是我希望。


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.

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:

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:

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.