绝对位置,但相对于父位置 [英] Position absolute but relative to parent

查看:100
本文介绍了绝对位置,但相对于父位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个div在另一个div,我想使用css定位一个孩子div到父div的右上角,另一个孩子div到父div的底部。也就是说,我想使用两个子div的绝对定位,但是它们相对于父div而不是页面来定位。我如何做到这一点?

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?

示例html:

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


推荐答案

#father {
   position: relative;
}

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

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

这是因为 position:absolute 表示像使用顶部底部 left 将自己定位于最近的祖先 position:absolute c>

This works because position: absolute means something like "use top, right, bottom, left to position yourself in relation to the nearest ancestor who has position: absolute or position: relative."

因此我们使 #father position:relative ,子元素 position:absolute ,然后使用 >和底部来定位孩子。

So we make #father have position: relative, and the children have position: absolute, then use top and bottom to position the children.

这篇关于绝对位置,但相对于父位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆