绝对定位到整个窗口

27

我有以下问题:我有一个父级div,其位置为“relative”。在这个div内,我有2个子级div。第一个子级div应该相对于父级div定位。但是第二个子级div应该相对于整个浏览器窗口定位。

我的HTML和CSS:

#father
{
  position:relative;
}
#son1
{
  position:absolute;
  left:0;
  top:0;
}
#son2
{
  position:absolute;
  left:670;
  top:140;
}
<div id='father'>
 <div id='son1'></div>
 <div id='son2'></div>
</div>

现在我的问题是,son2-div也是相对于father-div定位的。有没有可能告诉son2-div应该继承父级的“position:relative”并使左侧和顶部绝对绝对为整个窗口?

问题是:我需要在非常复杂的HTML结构中进行更改,因此无法更改HTML结构。


5
顶部的 div 被归类为父元素,里面的任何东西都被称为子元素。不是父子关系。可能值得注意一下。 - Ruddy
5个回答

22

首先,进行更改。

#son2
{
  position:absolute;
  left:670;
  top:140;
}

to
#son2
{
  position: fixed; /*change to fixed*/
  left:670px; /*add px units*/
  top:140px; /*add px units*/
}

Result:

#father
{ 
    position:relative;
    margin: 40px auto;
    width:200px;
    height: 200px;
    background: red
}
#son1
{
  position: absolute;
  left:0;
  top:0;
    
  width:20px;
    height: 20px;
    background: black
}
#son2
{
  position:fixed;
  left:70px;
  top:140px;
  width:200px;
  height: 200px;
  background: green
}
<div id='father'>
 <div id='son1'></div>
 <div id='son2'></div>
</div>


OP提到他的#father元素是相对定位的,而且他不能真正改变这一点。 - Praxis Ashelin
@DarkAshelin 抱歉没看到我使用了 position: fixed 来固定它。 - Gildas.Tambo
“position: fixed;” 可能无法正常工作,这取决于 OP 的布局。但如果在他的布局中可以正常工作,那么这将是一个简单的修复。 - Praxis Ashelin
1
适用于我的特定情况。谢谢! - derpedy-doo

8
很遗憾,在不改变HTML结构的情况下是不可能实现的。一个绝对定位的
会根据其第一个相对定位的父元素定位。
但是可能可以修改#father元素的宽度/高度以正确定位#son2元素。这实际上取决于你的布局,以及在不破坏布局的情况下你能够修改#father元素的程度。或者如果可能的话,更改CSS,以便您不需要在#son1上使用position:absolute;(之后您就可以从#parent中移除position:relative;)。

2
您应该将第二个子 div 放在父 div 外部。

1

#father
{
  background-color: blue;
  width: 200px;
  height: 200px;
}
#son1
{
  position:relative;
  left:0;
  top:0;
  background-color: red;
  width: 50px;
  height: 50px;
  
}
#son2
{
  position:absolute;
  left:670px;
  top:140px;
  background-color: yellow;
  width: 50px;
  height: 50px;
}
<div id='father'>
 <div id='son1'></div>
 <div id='son2'></div>
</div>

  1. 父级div不需要使用position: relative;
  2. 为了您的目的,son1应该使用position: relative;
  3. 我强烈建议使用background-color, widthheight来查看页面上div的位置。

另外,在您的代码中有一个简单的错误:

  left:670;
  top:140;

你应该指定测量单位;

  left:670px;
  top:140px;

0

你的div#son1默认已经被定位到div#father上(静态位置)。你不需要对它们设置任何位置。

#father
{
  /* don't set position.  it's static by default */
}
#son1
{
  /* don't set position.  It's positioned to #father by default */
  left:0;
  top:0;
}
#son2
{
  position:absolute;
  left:670;
  top:140;
}
<div id="father">
  <div id="son1"></div>
  <div id="son2"></div>
</div>

此外,如果您想将div#son2定位到窗口(用户可见区域),而不是根元素(body),则应将div#son2设置为 fixed
请观看此视频了解有关固定位置的更多详细信息。

https://www.youtube.com/watch?v=nGN5CohGVTI


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接