如何用CSS相对定位设置DIV的高度?
我有一些 HTML+CSS 代码想要布局几个 div
。布局是这样的:所有 div
都位于大小固定的父 div
中。然后每个子 div
应该保持在自己的行上,并使用最小高度来绘制其内容。最后一个 div
应消耗所有剩余高度,以便父级 div
被完全填充。
此代码显示了我使用 CSS float
和 clear
属性的方法:
<html>
<head>
<style>
.container {
width: 500px;
height: 500px;
border: 3px solid black;
}
.top {
background-color: yellow;
float: left;
clear: left;
width: 100%;
}
.bottom {
background-color: blue;
height: 100%;
float: left;
clear: left;
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<div class="top">top1</div>
<div class="top">top2</div>
<div class="top">top3</div>
<div class="top">top4</div>
<div class="bottom">bottom</div>
</div>
</body>
</html>
但是,最后一个 div
从其父级溢出。我猜这是因为 width: 100%
。
有什么办法可以解决这个问题吗?我想避免设置父级的 overflow
属性,而且我还必须避免使用绝对定位。如果我能以某种方式欺骗最后一个 div
使用父级的高度减去其他 div
的高度总和。
I have some HTML+CSS code that wants to layout several div
s. The layout is like this: all div
s stay in a parent div
whose size is fixed. Then each child div
should stay on its own line, and use the minimum height for drawing its content. The last div
should consume all remaining height, so that the parent div
is entirely filled.
This code shows my approach using CSS float
and clear
properties:
<html>
<head>
<style>
.container {
width: 500px;
height: 500px;
border: 3px solid black;
}
.top {
background-color: yellow;
float: left;
clear: left;
width: 100%;
}
.bottom {
background-color: blue;
height: 100%;
float: left;
clear: left;
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<div class="top">top1</div>
<div class="top">top2</div>
<div class="top">top3</div>
<div class="top">top4</div>
<div class="bottom">bottom</div>
</div>
</body>
</html>
However, the last div
overflows from the its parent. I guess it is because of the width: 100%
.
Is there any way to solve this problem? I want to avoid setting the overflow
attribute of the parent, and also I have to avoid using absolute positioning. If somehow I could trick the last div
to use the height of the parent minus the sum of height of the other div
s.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
添加:
它不会溢出,因为它是 100% 宽度。它溢出了,因为它是一个浮动,因此从正常布局中删除。更改溢出属性将改变浏览器处理包含的浮动的方式。
哦,如果您还没有,请确保您正在使用 DOCTYPE。这对于 IE 尤其重要。
Add:
It's not overflowing because it's 100% width. It's overflowing because it's a float and thus removed from the normal layout. Changing the overflow property will change how the browser caters for contained floats.
Oh and if you aren't already, make sure you're using a DOCTYPE. It particularly matters for IE.