首页 > 【css】position:absolute;是相对于那个元素定位?

【css】position:absolute;是相对于那个元素定位?

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

但是下面代码里的img和input怎么相对于body定位了?

<script src="jquery-1.12.1.js" type="text/javascript"></script>
  <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;
        }
    .head-photo img
        {
            position:absolute;
            top:15px;
            left:15px;
            display:none;
            z-index:10;
        }
    
    .upload-file
        {
            position:absolute;
            top:15px;
            left:15px;
            width:70px;
            height:48px;
            overflow: hidden;
            filter:alpha(opacity=0);
            opacity:0;
            z-index:15;
        }
  </style>
  <script>
    $(document).ready(function(){
        $('.head-photo').mouseover(function(){
            $('.x1').css('display','inline-block')}
    );
        $('.head-photo').mouseout(function(){
            $('.x1').css('display','none')}
    );
    });
  </script>
 </head>
 <body>
 <div class='head-photo'>

    <img src='' width=50px height=70px />
    <input class='upload-file' type='file'>
    <img class='x1' src='head-camera.gif' />
    
 </div>
 </body>

head-photo 设置相对定位,不设置它相对定位就会相对body定位


绝对定位一般都是和相对定位一起出现,如果父级元素没有相对定位position:relative;那么子级绝对定位会相对于body来定位


你都说了:生成绝对定位的元素,相对于static定位以外的第一个父元素进行定位。
元素默认的定位值是static,所以往上找参照元素一直到根元素了。
请为.head-photo元素添加属性position: relative


img和input的第一层父元素是div.head-photo,没有设置position属性的时候默认为static定位,再往上层就是顶层的body元素,因此是基于body元素定位计算left、top位置。

解决方法是设置div.head-photo的position属性,一般情况下设置为relative就可以了。

【热门文章】
【热门文章】