search

Home  >  Q&A  >  body text

Absolute position but relative to parent

I have two divs inside another div and I want to use css to position one child div to the top right corner of the parent div and the other child div to the bottom of the parent div. I.e. I want to use absolute positioning for the two child divs, but position them relative to the parent div instead of the page. How can I do this?

Example html:

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


P粉395056196P粉395056196411 days ago693

reply all(2)I'll reply

  • P粉509383150

    P粉5093831502023-10-12 10:05:38

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

    reply
    0
  • P粉567281015

    P粉5672810152023-10-12 09:56:03

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

    This is valid because position:absolute means "use top, right, bottom, left Position yourself relative to a nearest ancestor with position:absolute or position:relative."

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

    reply
    0
  • Cancelreply