css - Div左右对齐而不清除两者

标签 css position css-float

我有 6 个 div,红色和蓝色左右对齐。参见示例:

.blue{
    float:left;
    margin-bottom:10px;
    width:41%;
    height:auto;
    background:blue;
    }
.red{
    float:right;
    margin-bottom:10px;
    width:41%;
    height:auto;
    background:red;
    }
.demo{
    width:41%;
    height:100px;
    }
<div class="blue"><div class="demo"></div></div>
<div class="red"><div class="demo"></div></div>
<div class="blue"><div class="demo"></div></div>
<div class="red"><div class="demo"></div></div>
<div class="red"><div class="demo"></div></div>
<div class="blue"><div class="demo"></div></div>

没关系。但是如果 div demo2 中的内容更高,它将使 som 像这样:

.blue{
    float:left;
    margin-bottom:10px;
    width:41%;
    height:auto;
    background:blue;
    }
.red{
    float:right;
    margin-bottom:10px;
    width:41%;
    height:auto;
    background:red;
    }
.demo{
    width:41%;
    height:100px;
}
.demo2{
    width:41%;
    height:150px;
    }
<div class="blue"><div class="demo2"></div></div>
<div class="red"><div class="demo"></div></div>
<div class="blue"><div class="demo"></div></div>
<div class="red"><div class="demo"></div></div>
<div class="red"><div class="demo"></div></div>
<div class="blue"><div class="demo"></div></div>

不幸的是,我无法将它们包含到两个父 div(例如#left、#right)中,因为这些框需要长期排序。

我尝试使用 position/fixed/absolute/但没有任何反应。

最佳答案

您需要按照以下方式创建 html

    .parent{ float: left; height: auto; width: 100%; margin-bottom:10px; }
    
    .blue{ float:left; width:41%; height:100%; background:blue; } 
    
    .red{ float:right; width:41%; height:100%; background:red; } 
    
    .demo{ width:41%; height:100px; } 
    
    .demo2{ width:41%; height:150px; }
    <div class='parent' style='height:150px'> 
      <div class="blue"><div class="demo2"></div></div> 
      <div class="red"><div class="demo"></div></div> 
    </div> 

    <div class='parent'> 
      <div class="blue"><div class="demo"></div></div> 
      <div class="red"><div class="demo"></div></div> 
    </div> 

希望这个有用,如有疑问请回复

关于css - Div左右对齐而不清除两者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32523141/

相关文章:

css - 我正在使用旋转木马来显示图像,但无法使用无序列表修复图像以覆盖背景

html - firefox 在相对容器问题中的绝对位置

jquery - jQueryUI 图标中是否存在 CSS 错误

html - 向左浮动和向右浮动

javascript - 删除上一个 TR 中的样式

html - div不显示在页面中央

css - 彼此相邻 float 的大元素?

css - 尝试定位元素不起作用

php - 如何在 codeigniter 中引用 css 文件? 2.0

html - Bootstrap 行不占用 100% 宽度