How do I set the position of an element relative to another element?

Discussion in 'Web Design and Development' started by moonman239, Mar 1, 2013.

  1. macrumors 65816

    Joined:
    Mar 27, 2009
    #1
    I need to position an element directly below another element, but I don't know the element's position, and I don't want to take the time to figure it out. I could probably whip up a little script, but is that the only way, or can I do it all in CSS?
     
  2. macrumors 6502a

    Hexiii

    Joined:
    Jun 30, 2011
    Location:
    Prague, Czech Republic
    #2
    I think the element will be automatically under it. What element are you talking about?
     
  3. macrumors 68040

    elppa

    Joined:
    Nov 26, 2003
    #3
    I am not sure I am 100% certain of what you are asking, because you haven't really given enough information about the styling currently applied to the two elements in question.

    If you do have parent element which is relatively positioned then by making the child element absolutely positioned you will ensure the child is always positioned relative to its parent.

    By way of an example:

    Code:
    <!DOCTYPE html>
    
    <html>
    <head>
    	<title>Positioning Example</title>
    </head>
    
    <body>	
    	<div>
    		parent element
    		<div>child element</div>
    	</div>
    </body>
    </html>
    
    Code:
    div {
    	width: 200px;
    	height: 200px;
    }
    
    body > div {
    	position: relative;
    	background: #f00;
    	margin: 0 auto;
    }
    
    div > div {
    	position: absolute;
    	top: 200px;
    	left: 50px;
    	background: #ff0;
    }
    
    Thus you can easily position the child below the parent (provided you know the parents height).

    If the elements are floated, then you can just clear floats. That will put on element below another.

    We do probably need a bit more information about the current CSS properties applied to the elements to be able to help more though.
     
  4. macrumors 68000

    SrWebDeveloper

    Joined:
    Dec 7, 2007
    Location:
    Alexandria, VA, USA
    #4
    Elppa, maybe next time include ID's/classes in your div example because although "div > div" certainly is legal, it could be dangerous to use that example in a real site as some newbies would, affecting any div within another - what a potential mess. Using ID's/classes also helps newbies and guru's alike when debugging style issues, plus extremely useful if tied into Javascript methods.

    Yep, I admit fully I am being picky here. My apologies for that, but of course nothing personal intended and of course your advice was spot on, as always.

    Cheers to you, please don't kill me for this.

    :eek:
     

Share This Page