“position:absolute”div有没有办法保留相对宽度?

时间:2022-09-30 20:30:19

Let's say I have two divs, one inside the other, like so:

假设我有两个div,一个在另一个里面,就像这样:

<html>
<body>
<div id="outer" style="width:50%">
<div id="inner" style="width:100%">
</div>
</div>
</body>
</html>

Right now, the inner div has a width of 100% of 50% of the screen size, or 50% of the screen size. If I were to change the inner div to position absolute, like this:

现在,内部div的宽度为屏幕尺寸的50%的100%,或屏幕尺寸的50%。如果我要将内部div更改为绝对位置,如下所示:

<html>
<body>
<div id="outer" style="width:50%">
<div id="inner" style="position:absolute;width:100%">
</div>
</div>
</body>
</html>

In this case the inner div takes up 100% of the screen space, because its position is set to absolute.

在这种情况下,内部div占据屏幕空间的100%,因为它的位置设置为绝对。

My question is this: Is there any way to maintain relative width of the inner div while its position is set to absolute?

我的问题是:当它的位置设置为绝对时,有没有办法保持内部div的相对宽度?

2 个解决方案

#1


56  

Add position:relative to your outer div.

添加位置:相对于你的外部div。

update: It works because positions in position: absolute are relative to the first parent that has some positioning (other than static). In this case there was no such container, so it uses the page.

更新:它的工作原理是因为位置:绝对是相对于具有一定位置的第一个父级(静态除外)。在这种情况下,没有这样的容器,所以它使用页面。

#2


6  

Yes. Set outer to position: relative.

是。将外部设置为position:relative。

http://jsfiddle.net/57673/

http://jsfiddle.net/57673/

.outer
{
  width: 50%;
  height: 200px;
  position: relative;
  border: 1px solid red;
}

.inner
{
  width: 100%;
  position: absolute;
  height: 100%;
  border: 1px solid blue;
}

#1


56  

Add position:relative to your outer div.

添加位置:相对于你的外部div。

update: It works because positions in position: absolute are relative to the first parent that has some positioning (other than static). In this case there was no such container, so it uses the page.

更新:它的工作原理是因为位置:绝对是相对于具有一定位置的第一个父级(静态除外)。在这种情况下,没有这样的容器,所以它使用页面。

#2


6  

Yes. Set outer to position: relative.

是。将外部设置为position:relative。

http://jsfiddle.net/57673/

http://jsfiddle.net/57673/

.outer
{
  width: 50%;
  height: 200px;
  position: relative;
  border: 1px solid red;
}

.inner
{
  width: 100%;
  position: absolute;
  height: 100%;
  border: 1px solid blue;
}