1.定位有以下幾種:絕對定位,相對定位,fixed定位等
2.fixed定位是針對於整個頁面來說的,浮動於定點處,不適合,相對定位針對的是本來自己的位置,也不適合做相對於父元素的垂直左右居中,我們要用的是絕對定位
3.案例
先創建一個父盒子,一個子盒子:
<body>
<div class="father">
<div class="son">
</div>
</div>
</body>
<style>
.father{
width: 500px;
height: 500px;
">grey;
}
.son{
width: 100px;
height: 100px;
">red;
}
</style>
然后得到一個這樣的圖片

最后利用絕對定位來做:
<body> <div class="father"> <div class="son"> </div> </div> </body> <style> .father{ position: relative; width: 500px; height: 500px; background-color:grey; } .son{ position: absolute; top: 50%; left: 50%; margin-left: -50px; margin-top: -50px; width: 100px; height: 100px; background-color:red; } </style>
結果:

缺點:需要知道本身這個子盒子的寬度,利用margin-left、margin-top負一半寬度去調整
