首页 > 解决方案 > 边距不会在两个子元素之间创建空间,但填充可以

问题描述

查看盒子模型,边距是元素框外(边界外)的距离,而填充是内容和边界之间的距离。

假设我有两个子元素inner-top,并且inner-bottom都包含在outer例如


<div class="outer">
    <div class="inner-top">
        <img src = "some_image_url">
    </div>

    <div class="inner-bottom">
        Some text
    </div>
</div>

和CSS

img{
    height: 100%;
    max-width:100%;
}

.outer{
    background-color:rgb(53, 179, 80);
    width: 200px;
    height: 200px;
    position: relative;
}

.inner-top{
    margin:0 auto;
    background-color:rgb(49, 36, 170);
    width: 90%;
    height: 75%;
    margin-bottom: 10px; /* this does not create any room but does with padding*/

}

.inner-bottom{
    background-color:crimson;
    width:100%;
    height:25%;
    position:absolute;
    bottom:0
}

我想在inner-top和之间有 10px 的空间inner-bottom。由于它是两个不同的元素,我假设我们应该使用margin-bottomin inner-top(因为我们需要 room * after inner-top)但这样做不会产生任何空间。设置padding-bottom=10px创造房间。这是为什么?为什么这里不是边距,因为它是 和 之间的inner-top距离inner-bottom?如果它确实有影响,我也会导入 bootstrap4。

标签: htmlcss

解决方案


您可以从内部底层类中删除“位置:绝对”和“底部:0”,这种方式对我有用。

但是,如果您从未听说过 flex,这可能是您一直在等待的时刻 :) 这可能是更好的解决方案:

img{
    height: 100%;
    max-width:100%;
}

.outer{
    display: flex;
    flex-direction: column;
    background-color:rgb(53, 179, 80);
    position: relative;
    width: 200px;
}

.inner-top{
    margin:0 auto;
    background-color:rgb(49, 36, 170);
    width: 90%;
    height: 200px;
    margin-bottom: 10px; //margin is working now

}

.inner-bottom{
    background-color:crimson;
    width:100%;
    height:50px;
}

推荐阅读