Position a child div relative to parent container in CSS: [设置 子DIV位置 跟 父DIV相关联]

最近调DIV的位置比较头疼,各种position: relative / absolute

google到一篇好文章[http://www.webdevdoor.com/html-css/css-position-child-div-parent/]

如何让子div的位置相对父div的位置固定,而父div的位置可以变动。

重点是:父div一定要有position属性(不管relative还是absolute),子div就可以设置position:absolute,这时子div的位置是相对父div是固定的。

以下自己根据文章自己加了些改动,主要是测试当父div内部追加了div之后,看原来的子div的位置是否受影响,事实证明没影响。

<style>

.parent {

width:250px;

height:250px;

background-color:#CCCCCC;

position:relative;

}

.child {

width:100px;

height:100px;

background-color:#999999;

position:absolute;

//bottom:0px;

//right:0px;

top:100px;

left:100px;

}

</style>

<script type="text/javascript" src="jquery-1.7.1.min.js"></script>

<script>

function appendFront(){

$("#parentId").prepend("<div width:100px;height:50px; top:50px;background-color:#ffffff;\"></div>");

}

</script>

<div >click</a>