position:absolute相对哪个元素定位

应用了position: absolute的元素会循着节点树中的父(祖)元素来确定“根”,然后相对这个“根”元素来偏移。如果在其节点树中所有父(祖)元素都没有设置position属性值为relative或者absolute则该元素最终将对body进行位置偏移。应用了position: absolute的元素会脱离页面中的普通流并改变Display属性(重点)


w3school说:生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。

也就是说

生成绝对定位的元素,相对于static定位以外的第一个父元素进行定位。
元素默认的定位值是static,所以往上找参照元素一直到根元素了。
如果是要相对第一个父元素定位,请为该父元素添加属性position: relative,或者添加position:absolute

示例代码:

<html>
<head>
  <style>
    *{margin:0;border:0;padding:0;}
    .head-photo
        {
            margin-top:100px;
            margin-left:100px;
            width:100px;
            height:120px;
            border:5px solid green;
            text-align:center;
            position:relative;
        }
    .head-photo div
        {
            position:absolute;
            top:15px;
            left:15px;
            display:block;
            z-index:10;
			border:2px solid red;
			width:50px;
			height:70px;
        }
 
  </style>

 </head>
 <body>
 <div class='head-photo'>
    <div></div>   
 </div>
 </body>
</html>

或者设置.head-photo的position为absolute
<html>
<head>
  <style>
    *{margin:0;border:0;padding:0;}
    .head-photo
        {
            margin-top:100px;
            margin-left:100px;
            width:100px;
            height:120px;
            border:5px solid green;
            text-align:center;
			position:absolute;
        }
    .head-photo div
        {
            position:absolute;
            top:15px;
            left:15px;
            display:block;
            z-index:10;
			border:2px solid red;
			width:50px;
			height:70px;
        }
 
  </style>

 </head>
 <body>
 <div class='head-photo'>
    <div></div>   
 </div>
 </body>
</html>


结果都是:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值