CSS - float参数只在另一个部分的顶部堆叠的问题



float参数有问题,所以做了一个简单的代码片段来显示问题(当然它很简单,但不能精确定位)。

根据我对float声明的理解,它应该:

  • 将第一个section向上向左或向右移动
  • 下一节应该移动到第一部分的左边或右边,只要还有足够的宽度空间
  • 上面应该继续,直到宽度空间不可用,必须创建一个新的行

然而,这些节只是在声明中指定的一侧一个叠在另一个上。不能让他们靠近一个

header,
footer {
text-align: center;
height: 30px;
width: 100%;
border: 1px solid black;
clear: both;
}
section {
text-align: center;
height: 30px;
width: 20%;
float: left;
border: 1px solid black;
clear: both;
}
<header>Header</header>
<section>Section 1</section>
<section>Section 2</section>
<section>Section 3</section>
<footer>Footer</footer>

问题是"你可以用两种方式继续:

解决方案1:

如果你想使用"clear"样式规则必须应用于包含"float":

的部分(在示例中为div

)的父元素。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="index.css" />
<title>Document</title>
</head>
<body>
<header></header>
<div id="parent">
<section></section>
<section></section>
<section></section>
</div>
<footer></footer>
</body>
</html>

css头,页脚{身高:100 px;宽度:100%;边框:1px纯黑色;明确:;}

#parent {
clear: both; /* add this here and remove clear:both from section */
}
section {
height: 300px;
width: 20%;
float: left;
border: 1px solid black;
}

这样,包含section标签的行将被对齐,之后的所有内容将不会根据"float"给出的位置移动。clear属性用于防止其他浮动元素出现在元素旁边。它只适用于块元素,不能被继承。

解决方案2

仅从css

的section中删除clear:both

使用clear: both在你的部分是迫使他们去新的行,而不是堆叠在一起。

如果你删除它,只应用clear: both到你的页脚,它应该正常工作。

最新更新