绝对定位,溢出元素的百分比

时间:2013-12-07 04:00:48

标签: css overflow space percentage absolute

在以下网页(jsfiddle)中,我想要在顶部和底部有10%的空格。但是当div #b溢出时,容器内部的底部没有空间。有什么问题?

<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
#a {
    position: relative;
    width: 300px;
    height: 200px;
    overflow: auto;
    background: gray;
}
#b {
    position: absolute;
    top: 10%;
    bottom: 10%;
}
</style>
</head>
<body>
<div id="a">
<div id="b">
hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello 
</div>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

如果您为#b元素添加边框,

#b {
    position: absolute;
    top: 10%;
    bottom: 10%;
    border: 1px solid yellow;
}

您将看到顶部和底部10%的空间:http://jsfiddle.net/audetwebdesign/r4GD8/1/

但是,如果内容未填满200px高度的80%,您将看到文本与父级(灰色背景)容器底部之间的间隙较大。

你正在做的事情正确,但没有像你期望的那样可视化效果。

您可能尝试垂直居中,但这是一个不同的问题。

滚动溢出的面板

如果您希望#b的高度与其内容成比例增加,并且您希望在顶部和底部保留一些空白区域,那么您可以尝试:

#a {
    width: 300px;
    height: 200px;
    position: relative;
    overflow: auto;
    background: gray;
}

#b {
    position: absolute;
    min-height: 160px;
    padding: 10px 0;
}

#b高于200px时,#a将显示垂直滚动条。

除非您要将背景图片或颜色添加到min-height,否则#b上的#b属性并非绝对必要。

您需要指定填充的长度,使用百分比值基于父级的宽度(而不是您可能期望的高度)。

请参阅演示:http://jsfiddle.net/audetwebdesign/w9qTX/

答案 1 :(得分:1)

您可以将其更改为margin-bottom: 10%#b更改为position:relative

请参阅此jsFiddle example

#a {
    width: 300px;
    height: 200px;
    position: absolute;
    overflow: auto;
    background: gray;
}

#b {
    position: relative;
    top: 10%;
    margin-bottom: 20%;
}