html - 边距不会在两个子元素之间创建空间,但填充可以
问题描述
查看盒子模型,边距是元素框外(边界外)的距离,而填充是内容和边界之间的距离。
假设我有两个子元素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-bottom
in inner-top
(因为我们需要 room * after inner-top
)但这样做不会产生任何空间。设置padding-bottom=10px
创造房间。这是为什么?为什么这里不是边距,因为它是 和 之间的inner-top
距离inner-bottom
?如果它确实有影响,我也会导入 bootstrap4。
解决方案
您可以从内部底层类中删除“位置:绝对”和“底部: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;
}
推荐阅读
- python - 访问消费者柯南食谱中的导出文件
- reactjs - mobx - 越界读取:0
- python - Google Colab 的 Traceback(最近一次通话最后一次)run_model(**vars(args))
- rust - 我可以在闭包中通过引用和值来捕获一些东西吗?
- excel - Excel 解释日期错误
- html - 表行增长到最大?
- javascript - 有没有办法以编程方式(在 JS 中)要求用户允许在 Safari 中自动播放?
- reactjs - 如何对 React-table 中的两列使用相同的访问器?
- c++ - 在派生类中实例化基类中定义的结构
- javascript - 响应斜杠命令