为什么在css上应用浮点数时div元素会被压扁?

问题描述 投票:0回答:1

我对这段代码有几个问题: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
1个回答
0
投票

你的第四个元素被压扁,因为你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

© www.soinside.com 2019 - 2024. All rights reserved.