css-float - 为什么在 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>
解决方案
您的第四个元素被压扁,因为您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
的百分比。
推荐阅读
- java - 无法从 groovy 中的 json 数组中过滤对象
- python - 在 json 中发出不带双引号的 HTTP 请求
- dom - 如何使用 puppeteer 检查数据选择器是否不在屏幕上
- android - 基于焦点的DataBinding后台drawable更新
- python - 解压缩 TIFF 文件
- java - 应用程序中的日期可以,但在数据库中保存 -2 小时
- python - python3:.strip() 没有按预期工作
- java - 尽管有缺口,如何全屏显示?
- java - 具有不同查询参数类型的 Spring REST 端点
- flutter - 如何在flutter中使用firebase通过电话身份验证检查用户是否登录?