How to set relative position with Grandfather! element?

眉间皱痕 提交于 2020-07-07 09:26:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!