Html 位置绝对但相对于父级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10487292/
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 00:13:52  来源:igfitidea点击:

Position absolute but relative to parent

htmlcss

提问by BlaShadow

I have two divs inside another div, and I want to position one child div to the top right of the parent div, and the other child div to the bottom of the parent div using css. Ie, I want to use absolute positioning with the two child divs, but position them relative to the parent div rather than the page. How can I do this?

我在另一个 div 中有两个 div,我想使用 css 将一个子 div 定位到父 div 的右上角,将另一个子 div 定位到父 div 的底部。即,我想对两个子 div 使用绝对定位,但将它们相对于父 div 而不是页面定位。我怎样才能做到这一点?

Sample html:

示例 html:

<div id="father">
   <div id="son1"></div>
   <div id="son2"></div>
</div>

回答by Domenic

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 0;
}

#son2 {
   position: absolute;
   bottom: 0;
}

This works because position: absolutemeans something like "use top, right, bottom, leftto position yourself in relation to the nearest ancestor who has position: absoluteor position: relative."

这工作,因为position: absolute手段类似“使用toprightbottomleft来定位自己相对于谁拥有最近的祖先position: absoluteposition: relative”。

So we make #fatherhave position: relative, and the children have position: absolute, then use topand bottomto position the children.

所以我们让#fatherhave position: relative,孩子 has position: absolute,然后使用topbottom来定位孩子。

回答by Brian Warshaw

div#father {
    position: relative;
}
div#son1 {
    position: absolute;
    /* put your coords here */
}
div#son2 {
    position: absolute;
    /* put your coords here */
}

回答by petergus

Incase someone wants to postion a child div directly under a parent

如果有人想将子 div 直接放置在父级下方

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 100%;
}

Working demo Codepen

工作演示Codepen

回答by anam

If you don't give any position to parent then by default it takes static. If you want to understand that difference refer to this example

如果你没有给父母任何位置,那么默认情况下它需要static. 如果您想了解这种差异,请参阅此示例

Example 1::

示例 1::

http://jsfiddle.net/Cr9KB/1/

http://jsfiddle.net/Cr9KB/1/

   #mainall
{

    background-color:red;
    height:150px;
    overflow:scroll
}

Here parent class has no position so element is placed according to body.

这里父类没有位置,所以元素是根据主体放置的。

Example 2::

示例 2::

http://jsfiddle.net/Cr9KB/2/

http://jsfiddle.net/Cr9KB/2/

#mainall
{
    position:relative;
    background-color:red;
    height:150px;
    overflow:scroll
}

In this example parent has relative position hence element are positioned absolute inside relative parent.

在这个例子中,父元素具有相对位置,因此元素绝对定位在相对父元素内。