首页 > 解决方案 > 如何停止 div 的重叠?

问题描述

当我为容器设置浮动到右侧时,这种重叠发生,这是什么原因如何避免它?我希望黄色 div 低于红色 div,红色 div 应该在右边...

.container {
    float: right;
    height: 150px;
    margin: 10px;
    width: 50%;
    display: flex;
    flex-direction: row;
    /* flex-wrap: wrap; */
    justify-content: center;
    align-items: center;
    background-color: yellow;
}
<div class="container"></div>
<div style="display: block; margin: auto; background-color: red; height: 200px; width: 100%;"></div>

在此处输入图像描述

标签: htmlcsscss-float

解决方案


使用红色规则clear: both div

这是一个关键字,指示元素向下浮动以清除左右浮动。

.container {
    float: right;
    height: 150px;
    margin: 10px;
    width: 50%;
    display: flex;
    flex-direction: row;
    /* flex-wrap: wrap; */
    justify-content: center;
    align-items: center;
    background-color: yellow;
}
<div class="container"></div>
<div style="display: block; margin: auto; background-color: red; height: 200px; width: 100%; clear: both;"></div>


推荐阅读