绝对位置不在父级内 [英] Position absolute not inside parent
问题描述
我的CSS关于div位置有问题.
I have a problem with my CSS regarding div positions.
我有一个设置为 position:relative
的父div和一个设置为 position:absolute
I have a parent div which is set to position:relative
and a child div set to position:absolute
但是由于某种原因,子div显示在父div的边框下方和外部...
But for some reason the child div is displaying below and outside the borders of the parent div...
这是我的CSS:
.big{
position:relative;
width:40%;
border:1px solid black;
display:inline-block;
}
.small{
position:absolute;
width:75px;
height:75px;
border:1px solid green;
}
HTML:
<div class="big">
<p align="center">Test</p>
<div class="small"></div>
</div>
<div class="big">
<p align="center">Test</p>
<div class="small"></div>
</div>
我提供了一个JSFiddle来向您展示它的作用:
I have provided a JSFiddle to show you it in action:
当使用 position:absolute
时,如何解决该问题以使子div处于父div内?
How do i fix it to make the child div be inside the parent div whilst using position:absolute
for it?
推荐答案
您不能使用 position:absolute
来执行此操作,因为它会从文档流中删除元素.父对象上的 position:relative
会更改 position:absolute
相对位置的位置,但不会扩展为包含 position:absolute
.您将需要设置固定高度或使用 position:relative
.
You can't do this using position: absolute
as it removes the element from the document flow. position: relative
on the parent will change where the position: absolute
is positioned relative to, but it will not expand to contain the position: absolute
. You will need to set a fixed height or using position: relative
instead.
注意,如果在示例中使用 position:relative
,则需要添加等于 top
值的 margin-bottom
使它扩展为包含 position:relative
.请参见以下示例: http://jsfiddle.net/yV5q6/
Note, if using position: relative
in your example, you will need to add a margin-bottom
equal to the value of top
to make it expand to contain the position: relative
. See this example: http://jsfiddle.net/yV5q6/
这篇关于绝对位置不在父级内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!