1、position:fixed
该属性是 固定在浏览器的某个位置,针对的是全局
(1)top:40px;距离顶部的距离为40px;left:20px;距离左边的距离为20px;
<body> <div style=" 40px;height: 25px;background-color: black;color: white; position:fixed; top:40px; left:20px; ">返回</div> <div style="height:500px;background-color:#dddddd">123</div> </body>
执行结果如下:
(2)以下还是一个position:fixed的例子:
在position:fixed;中使用margin:0 auto(居中)失效。
margin-top:50px;为body距离头部50px;
<head> <meta charset="UTF-8"> <title>Title</title> <style> .pg-header{ height:48px; background-color:red; color:#dddddd; position:fixed; top:0; left:0; right:0; } .pg-body{ background-color: #dddddd; height: 500px; margin-top:50px; } </style> </head> <body> <div class="pg-header">头部</div> <div class="pg-body">内容</div> </body>
执行结果如下:
2、position:relative;position:absolute;
这两个属性一般配合使用,relative在浏览器固定一个大的框架;absolute在这个框架中固定某个位置
margin:0 auto;居中
为了好区分,我在此加了p标签
<body> <div style="position:relative;border:1px red solid;300px;height:60px;margin:0 auto"> <div style="position:absolute;left:0;bottom:0;30px;height:30px;background-color:blue"> </div> </div>
<p></p> <div style="position:relative;border:1px red solid;300px;height:60px;margin:0 auto"> <div style="position:absolute;right:0;top:0;30px;height:30px;background-color:blue"> </div> </div> </body>
执行结果如下:relative为外边红色的边框及边框里面;position为蓝色小块
3、position之三层背景
z-index; 谁的div的该值大,哪个div的背景在上面;
opacity:0.5;设置当前背景的透明度,该值越小越透明;
display:none;可以隐藏某个背景
在position:fixed;中使用margin:0 auto(居中)失效。
<body> <div style="z-index:10; position:fixed; top:50%; left:50%; margin-left:-250px; margin-top:-200px; background-color:white; height: 400px; 500px;"> <!-- 由于margin:0 auto在position:fixed;中使用失效; 故使用top:50%,left:50%想要使其居中,发现这两个属性是使白色方框块的左上定点居中,要想使其整体居中,在向左退250px,向上退200px,使用margin-left:-250px-
<input type="text"/> <input type="text"/> <input type="text"/> </div> <div style="z-index:8;position:fixed;background-color:black; top:0; bottom:0; right:0; left:0; opacity:0.4"> </div> <div style="height:500px;background-color:green"> 123456 </div> </body>
执行结果如下: