Html “位置:绝对”div 有没有办法保持相对宽度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14327104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:57:51  来源:igfitidea点击:

Is there any way for "position:absolute" div to retain relative width?

htmlcsspositionabsolute

提问by Charles

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 的位置设置为绝对时保持其相对宽度?

回答by Bror

Add position:relativeto your outer div.

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

update: It works because positions in position: absoluteare 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.

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

回答by Eli Gassert

Yes. Set outer to 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;
}