html - 3 个盒子正确堆叠所需的 CSS float 帮助

标签 html css layout

我在使用 float 创建特定布局时遇到问题。问题是需要三个盒子/容器才能让第一个盒子和第三个盒子在同一行上,而第二个盒子放在它们下面。我似乎只能让第二个盒子漂浮到第三个盒子。但是我希望第三个框向右浮动,而第一个框向左浮动。如果你看到代码笔中的代码,我的目标是让绿色框与红色框和它们下方的蓝色框对齐。谢谢!

https://codepen.io/benjiesongsong/pen/VwZpRGN

.container {
  width: 1200px;
  overflow: auto;
  margin: 0 auto
}

.box1 {
  width: 800px;
  height: 400px;
  background: red;
  float: left;
}

.box2 {
  width: 800px;
  height: 400px;
  background: blue;
  float: left;
}

.box3 {
  width: 400px;
  height: 400px;
  background: green;
  float: right;
}
<div class="container">
  <div class="box1"></div>
  <div class="box2"></div>
  <div class="box3"></div>
</div>

最佳答案

只要您使用 float ,codepen 中的 order 设置就没有效果(它们只适用于 flexbox 子级)——您必须更改 HTML 代码中元素的顺序。

.container {
  width: 1200px;
  overflow: auto;
  margin: 0 auto
}

.box1 {
  width: 800px;
  height: 400px;
  background: red;
  float: left;
}

.box2 {
  width: 800px;
  height: 400px;
  background: blue;
  float: left;
}

.box3 {
  width: 400px;
  height: 400px;
  background: green;
  float: right;
}
<div class="container">
  <div class="box1"></div>
  <div class="box3"></div>
  <div class="box2"></div>
</div>

但是如果你使用 flexbox,你可以按照你在 HTML 中的顺序来做,使用 display: flexflex-wrap 对于容器和子元素的 order 设置:

.container {
  width: 1200px;
  overflow: auto;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap
}

.box1 {
  width: 800px;
  height: 400px;
  background: red;
  order: 1;
}

.box2 {
  width: 800px;
  height: 400px;
  background: blue;
  order: 3;
}

.box3 {
  width: 400px;
  height: 400px;
  background: green;
  order: 2;
}
<div class="container">
  <div class="box1"></div>
  <div class="box2"></div>
  <div class="box3"></div>
</div>

关于html - 3 个盒子正确堆叠所需的 CSS float 帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57662921/

相关文章:

javascript - 第二次单击按钮不起作用(JQuery)

javascript - 带 SVG 的 Tabby JS 防止滚动

css - 获取 html 链接以激活 css 图像映射悬停

css - 使用 awk/gawk 修改 css

java - 是否有任何类型的 Android 布局文件导入?

html - 使我的 DIV 拉伸(stretch)以在 IE 中使用有效的 CSS 填充可用页面空间

html - 当 parent 的高度通过 padding-top 设置时设置 child 的高度

jquery - 在 jQuery 中按字母和数字排序

android - 自定义标题栏定位

html - 如何在 HTML 和 CSS 中进行此布局?