lowerkey
lowerkey

Reputation: 8335

positioning an element absolutely *within* another element

This question goes to the css wizards. I've googled this and couldn't find an answer. At this point I'm not sure it's possible:

How do I specify the position of an element within another element, semi-absolutely so to speak?

I want to say "Put element inner x pixels to the right of outer's left border, no matter where outer happens to be at the moment."

This might be possible with javascript, but shouldn't it be possible with css?

Upvotes: 0

Views: 985

Answers (2)

Gordon Gustafson
Gordon Gustafson

Reputation: 41239

#inner {
    position: absolute;
    left: 10px;
}

What this CSS actually does is position the #inner element 10px from the left border of its 'closest' parent that is has a position value of absolute, relative, or fixed. If no such element is found, it is absolute positioned relative to the body element, but if you make sure that the inner element has a parent that has its position defined with CSS, it will be positioned absolutely within that parent.

Take a look at this JSFiddle. First, look at the html and CSS to see how it was constructed, then go ahead and use your mouse to drag either of the element around (that's what the javascript in their does, its purely for demonstration purposes). Notice how when you drag the outer element, the inner one moves with it? All you are doing when you drag the elements around is changing the values of their top and left properties, and since its parent is absolute positioned, the child element will stay at the same spot within it no matter where you move it on the screen. :D

Upvotes: 4

Adam Jenkins
Adam Jenkins

Reputation: 55762

Absolutely, it's easy! All you have to do is specify the parent to have a position (either relative or absolute) and then the absolutely positioned child will be positioned "relative" to the closest positioned parent.

Confused?

Upvotes: 1

Related Questions