“位置:绝对"有什么办法吗?div 保留相对宽度? [英] Is there any way for "position:absolute" div to retain relative width?

查看:32
本文介绍了“位置:绝对"有什么办法吗?div 保留相对宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<身体><div id="outer" style="width:50%"><div id="inner" style="width:100%">

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

<身体><div id="outer" style="width:50%"><div id="inner" style="position:absolute;width:100%">

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

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

解决方案

position:relative 添加到您的外部 div.

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

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

<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:

<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.

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

解决方案

Add position:relative to your outer 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.

这篇关于“位置:绝对"有什么办法吗?div 保留相对宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆