首页 文章

绝对位置但相对于父级

提问于
浏览
341

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

示例html:

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

4 回答

  • 4
    #father {
       position: relative;
    }
    
    #son1 {
       position: absolute;
       top: 0;
    }
    
    #son2 {
       position: absolute;
       bottom: 0;
    }
    

    这是有效的,因为 position: absolute 意味着“使用 toprightbottomleft 来定位自己与最近的祖先 position: absoluteposition: relative 的关系 . ”

    所以我们让 #fatherposition: relative ,孩子们有 position: absolute ,然后使用 topbottom 定位孩子 .

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

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

    Example 1::

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

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

    这里父类没有位置,因此元素根据主体放置 .

    Example 2::

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

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

    在此示例中,父项具有相对位置,因此元素位于相对父项内的绝对位置 .

  • 23

    如果有人想直接在父母下面设置一个子div

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

    工作演示Codepen

相关问题