CSS的相对定位

王朝学院·作者佚名  2016-05-24  
宽屏版  字体: 小 | 中 | 大 | 超大  

CSS的相对定位CSS的相对定位:一.基本概念:顾名思义,此种定位是相对某一个对象进行的偏移,相对定位并不能使对象脱离文档流,尽管它的位置可能产生偏移,但是对象初始位置仍然会被保留。如果要真正掌握此种定位方式,搞清楚需相对于哪个对象进行偏移是关键点。二.如何将一个元素设置为响度定位:当一个对象的position属性值被设置为relative的时候就会发生相对定位:

position:relative

三.定位参考对象:可以使用top属性和left属性设置相对定位对象的偏移量。相对定位的偏移参考对象是此对象本身。代码实例:首先看一个没有使用定位的代码实例:

<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>CSS相对定位-蚂蚁部落</title> <style type="text/css"> .father { width:400px; height:400px; background-color:green; margin:50px; } .first { width:100px; height:100px; background-color:red } .second { width:100px; height:100px; background-color:blue } </style> </head> <body> <div class="father"> <div class="first"></div> <div class="second"></div> </div> </body> </html>

在以上代码中,所有的对象都没有采用相对定位,这里无须多介绍了。再来看一段采用相对定位的代码:

<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>CSS相对定位-蚂蚁部落</title> <style type="text/css"> .father { width:400px; height:400px; background-color:green; margin:50px; } .first { width:100px; height:100px; background-color:red; position:relative; left:20px; top:30px; } .second { width:100px; height:100px; background-color:blue } </style> </head> <body> <div class="father"> <div class="first"></div> <div class="second"></div> </div> </body> </html>

在以上代码中,first元素采用了相对定位,并产生偏移,偏移是以对象没有产生偏移前的位置为参考的。同时也可以看出,first元素的偏移前的位置依然会被保留,它周边的元素不能够占据。特别说明:定位元素经常与z-index属性一起使用,具体可以参阅CSS的z-index属性用法详解

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有