对于网页页面布局来说,使用定位可以简单粗暴地将各块区域布置好,并且实现多种特效。
绝对定位:
<!DOCTYPE html><html lang="en"> ???<head> ???????<meta charset="UTF-8"> ???????<title>Title</title> ???????<style> ???????????.box0{ ?width: 200px; height: 200px; position: relative;background: #cfa } ???????????.box0-1,.box0-2{ ?width: 50px; height: 50px; } ???????????.box0-1{ ?position:absolute; left: 50px; top: 50px; background: #567 ?} ???????????.box0-2{ ?position:absolute; left: 50px; top: 50px; background: #5a2} ???????</style> ???</head> ???<body> ???<div class="box0"> ???????<div class="box0-1">0-1</div> ???????<div class="box0-2">0-2</div> ???</div> ???</body></html>
结果如下:
0-1
0-2
需要注意的是,使用绝对定位调整元素在父级元素区域位置时,父级元素必须为非静态定位,否则子元素会往上级找到非静态的祖先元素,再依据其位置进行定位。
如果不适用定位,要实现这样的效果,需要使用CSS属性为:
.box0{ ?width: 200px; height: 200px;background: #cfa; overflow: hidden }.box0-1,.box0-2{ ?width: 50px; height: 50px; }.box0-1{ ?margin: 50px 0 0 50px; ?}.box0-2{ ?margin: 0 50px 0 100px; }
使用边距和浮动是一个计算的过程,需要把握好每一个像素之间的关系。而使用绝对定位就是单纯的找位置,只要量得住,那就找的准,直接粗暴。需要注意的是,绝对定位的元素脱离了标准文档流,其本身的位置并不会保留,所以不能和浮动同时使用。并且也不建议和margin一起使用。
对于相对定位来说,由于元素本身的位置并不会消失,所以配合浮动更加好用,否则使用绝对定位更方便。
如下(便于观察,两个小块设置100的上外边距,此时原本位置应从下方3/4开始):
<!DOCTYPE html><html lang="en"> ???<head> ???????<meta charset="UTF-8"> ???????<title>Title</title> ???????<style> ???????????.box1{ ?width: 200px; height: 200px; background: #abc } ???????????.box1-1,.box1-2{ width: 50px; height: 50px; margin-top: 100px; float: left; position: relative; } ???????????.box1-1{ ?top: 50px; left: 50px; background: #a2c; } ???????????.box1-2{ ?bottom: 50px; right: 50px; background: #22c; } ???????</style> ???</head> ???<body> ???<div class="box1"> ???????<div class="box1-1">1-1</div> ???????<div class="box1-2">1-2</div> ???</div> ???</body></html>
结果如下:
1-1
1-2
相对定位的相对,就是指没有设置定位值,元素所在的位置,根据代码顺序,后者会对前者内容进行覆盖。
绝对定位就是牛皮藓,固定在显示区域的位置,此时固定是针对显示区域而言,对于绝对定位,也不能和浮动使用,同样不建议与margin使用。
<!DOCTYPE html><html lang="en"> ???<head> ???????<meta charset="UTF-8"> ???????<title>Title</title> ???????<style> ???????????.box2{ ?width: 200px; height: 200px; background: #ca9 } ???????????.box2-1{ width: 50px; height: 50px; ??position: fixed; } ???????????.box2-1{ ?top: 50px; left: 50px; background: #4b3; } ???????</style> ???</head> ???<body> ???<div class="box2"> ???????<div class="box2-1">我被固定了</div> ???</div> ???</body></html>
结果自己找吧:
结果不是根据父级元素定位的,显示不出(和上一篇的旋转一样)暂时不知道为什么。
总之,不同的定位方式有不同的作用,使用定位的目的是让代码简洁直观,所以具体使用哪一种应当根据实际情况而定。
CSS定位使用方法
原文地址:http://www.cnblogs.com/zzmiaow/p/7675137.html