首页 > 解决方案 > 为什么在 css 上应用浮点数时 div 元素被压扁?

问题描述

我对这段代码有几个问题: 1.第四个div似乎被压扁了。它height比其他 div 小。2. 容器高度div没有变化到50%。我用过wv,但我不确定为什么 % 不起作用。

https://codepen.io/anon/pen/drERNr

.container {
	background: blue;
	width: 75%;
	height: 50vw;
}


.box {
	width: 20%;
	background: #333;
	color: white;
	font-size: 25px;
	font-family: 'helvetica';
	border: 1px solid blue;
	margin: 2px;
	float: left;
	text-align: center;
}

#box4 {
	width: 20%;
	background: #333;
	color: white;
	font-size: 25px;
	font-family: 'helvetica';
	border: 1px solid blue;
	margin-top: 2px;
	text-align: center;
}
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="index.css">
  <title>prac</title>
</head>
<body>
  <div class="container">
    <div id="one" class="box">
      <p>One</p>
    </div>
    <div id="two" class="box">
      <p>Two</p>
    </div>
    <div id="three" class="box">
      <p>Three</p>
    </div>
    <div id="box4">
      <p>four</p>
    </div>
  </div>
</body>
</html>

标签: css-float

解决方案


您的第四个元素被压扁,因为您float将前三个元素设置为left,但不要“重置” float. 这可以通过以下方式实现clearfix

#box4:before {
  content: "";
  display: table;
  clear: both;
}

.container {
  background: blue;
  width: 75%;
  height: 50vw;
}

.box {
  width: 20%;
  background: #333;
  color: white;
  font-size: 25px;
  font-family: 'helvetica';
  border: 1px solid blue;
  margin: 2px;
  float: left;
  text-align: center;
}

#box4:before {
  content: "";
  display: table;
  clear: both;
}

#box4 {
  width: 20%;
  background: #333;
  color: white;
  font-size: 25px;
  font-family: 'helvetica';
  border: 1px solid blue;
  margin-top: 2px;
  text-align: center;
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="index.css">
  <title>prac</title>
</head>

<body>
  <div class="container">
    <div id="one" class="box">
      <p>One</p>
    </div>
    <div id="two" class="box">
      <p>Two</p>
    </div>
    <div id="three" class="box">
      <p>Three</p>
    </div>
    <div id="box4">
      <p>four</p>
    </div>
  </div>
</body>

</html>

至于为什么不能%在 上使用.container,这是因为基于百分比的单位从直接父级(并向上链接)继承其值,但<body>没有固定height定义。您需要height对父级进行计算,以便子级能够计算自己height的百分比。


推荐阅读