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. moonman239 macrumors 68000

    Mar 27, 2009
    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. Hexiii macrumors 65816


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


    Nov 26, 2003
    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:

    <!DOCTYPE html>
    	<title>Positioning Example</title>
    		parent element
    		<div>child element</div>
    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. SrWebDeveloper macrumors 68000


    Dec 7, 2007
    Alexandria, VA, USA
    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.


Share This Page