DIV布局之position详解

相对定位和绝对定位

定位标签:position 
包含属性:relative(相对) absolute(绝对) 
1.position:relative; 如果对一个元素进行相对定位,首先它将出现在它所在的位置上。然后通过设置垂直或水平位置,让这个元素"相对于"它的原始起点进行移动。(再一点,相对定位时,无论是否进行移动,元素仍然占据原来的空间。因此,移动元素会导致它覆盖其他框)

2.position:absolute; 表示绝对定位,位置将依据浏览器左上角开始计算。 绝对定位使元素脱离文档流,因此不占据空间。普通文档流中元素的布局就像绝对定位的元素不存在时一样。(因为绝对定位的框与文档流无关,所以它们可以覆盖页面上的其他元素并可以通过z-index来控制它层级次序。z-index的值越高,它显示的越在上层。)

3.父容器使用相对定位,子元素使用绝对定位后,这样子元素的位置不再相对于浏览器左上角,而是相对于父窗口左上角

4.相对定位和绝对定位需要配合top、right、bottom、left使用来定位具体位置,这四个属性只有在该元素使用定位后才生效,其它情况下无效。另外这四个属性同时只能使用相邻的两个,不能即使用上又使用下,或即使用左,又使用右。

下面是一个DIV内多个DIV的相对绝对布局:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>testdiv.html</title>
    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3" />
    <meta http-equiv="description" content="this is my page"/>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    
    <script type="text/javascript">
        window.onload = function(){
            document.getElementById("mydiv").style.height = "200px";
        };
    </script>
  </head>
  
  <body>
      关键因素:外层加position:relative,里面的div使用position: absolute,<br />
      但这种方法的问题有:外层的div必须指定具体的height,高度不能使用百分比
   <!--  <div style="position:relative; 600px;height:500px;">
        <div style=" 100px;height: 50px; position: absolute;right:10px;bottom: 10px"></div>
    </div> -->
    
     <div id="mydiv" style="position:relative; 100%;height:auto;">
        <div style=" 100px;height: 50px; position: absolute;right:10px;bottom: 10px"></div>
        <div style=" 100px;height: 50px; position: absolute;left:10px;bottom: 10px"></div>
    </div>
  </body>
</html>

效果图:

原文地址:https://www.cnblogs.com/yangzhilong/p/3786213.html