position绝对定位以哪个对象为参考

快乐打工仔 分类:实例代码

position绝对定位以哪个对象为参考属于前端实例代码,有关更多实例代码大家可以查看

既然是定位,那么肯定就有参考对象,否则就无所谓定位了。

下面先看一个例子: 

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style type="text/css"> 
.parent{ 
  width:300px; 
  height:200px; 
  border:1px solid red; 
} 
.children{ 
   width:200px; 
   height:100px; 
   background-color:green; 
   position:absolute; 
   top:50%; 
   left:50%; 
} 
</style> 
</head> 
<body> 
<div class="parent"> 
<div class="children"></div> 
</div> 
</body> 
</html>

可能在我们第一理解中,绝对定位的参考对象是父对象,但是从上面代码的表现来看并非如此,上面代码中子对象绝对定位的参考对象是浏览器客户区。

下面我们修改一下代码: 

<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.pipipi.net/" /> 
<title>前端教程网</title> 
<style type="text/css"> 
.parent{ 
  width:300px; 
  height:200px; 
  border:1px solid red; 
  position:relative; 
} 
.children{ 
  width:200px; 
  height:100px; 
  background-color:green; 
  position:absolute; 
  top:50%; 
  left:50%; 
} 
</style> 
</head> 
<body> 
  <div class="parent"> 
  <div class="children"></div> 
</div> 
</body> 
</html>

在父对象中加上position:relative后,子对象的绝对定位参考对象即为父对象,其实只要父对象的定位方式不是static,那么子对象的绝对定位方式都会是父对象,否则参考对象就是浏览器客户区。更多相关内容可参阅绝对定位一章节。

注意:这里所说的窗口大家不要误认为是body,而是body的容器html,如果清除body的外边距的话,body就好像是浏览器客户区。

position绝对定位以哪个对象为参考,这样的场景在实际项目中还是用的比较多的,关于position绝对定位以哪个对象为参考就介绍到这了。

回复

我来回复
  • 暂无回复内容