css: position的使用;

position有四种模式: static, relative, position, fixed;

1、static(静态定位):默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。

2、relative(相对定位):生成相对定位的元素,通过top,bottom,left,right的设置相对于其正常(原先本身)位置进行定位。可通过z-index进行层次分级。  

3、absolute(绝对定位):生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。可通过z-index进行层次分级。

4、fixed(固定定位):生成绝对定位的元素,相对于浏览器窗口进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。可通过z-index进行层次分级。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body{ 90%; height:90%; text-align:center;}
.a{
	margin:0 auto; 
	background-color:#999;
	}
.test{position:relative; left:0px;top:0px; 100%;height:300px; background-color:#CCC; overflow:hidden;}
.b{ position:absolute; left:0px; top:0px; right:0px; bottom:0;margin:auto;100px; height:100px; background-color:#F00;z-index:10;}
.c{ position:absolute; left:200px; top:100px; 200px; height:200px; background-color:#FF0;z-index:20;}
</style>
<title>无标题文档</title>
</head>
<div class="a">
<div  class="test">
<div class="c"></div>
<div class="b"></div>
</div>
</div>
<body>
</body>
</html>

 注: absolute是相对最近的带定位属性的元素,使用left, right,top,bottom进行定位(left, right只能使用一个,top,bottom也是一样);

看上面的代码中,.b实现的是绝对定位居中, 需要设置position为absolute,left,right,top,bottom均为0, 最重要的是设置margin:auto; 这样就实现了水平,垂直居中,如果只要实现水平居中,可以删掉top,bottom的设置,反之,删掉left、right的设置;

原文地址:https://www.cnblogs.com/yinwei-space/p/10132898.html