问题
I have a layout like this:
<div class='one'>
<div class='two'>
<div class='three'>some text</div>
</div>
</div>
Is possible to set relative position for three according to grandfather element (one
) in CSS?
Look this: http://jsfiddle.net/chalist/H48Je/
回答1:
When an element has position: relative
and you move it (say left: 20px
) it moves in relation to its natural position in the flow of the page, leaving a gap where it was before (which no other element will grab, as it were). So in a way, the simple answer is yes: if you give .three
a relative position and move it, it will move in relation to all its ancestors.
Generally, though, if you want to move an element in relation to an ancestor, you'd normally give the ancestor position: relative
and the element that's being moved position: absolute
. Then any positioning (e.g. top: 20px
) will be in relation to the positioned ancestor, and the element being moved won't leave a gap behind.
The one thing to note is that this positioning will be in relation to the nearest positioned ancestor. So if .two
has positioning, you won't be able to position .three
in relation to .one
... (not directly, anyway).
BTW, if an element is set to position: absolute
and no ancestor has any positioning set, any co-ordinates set on the absolute element will be in relation to the viewport.
来源:https://stackoverflow.com/questions/16774983/how-to-set-relative-position-with-grandfather-element