CSS 定位

来源:互联网 发布:淘宝流量钱包规则 编辑:程序博客网 时间:2024/06/03 12:57

在css中,如果你要确定一个元素的位置,那么就需要用到定位的属性了,属性名:position。

在css中,定位的方式有:static、fixed、relative、absolute。

(1)static 静态定位 (在网页中所有元素默认都是静态定位),即无定位,元素正常出现了流中。

(2)fixed 固定定位,选择该属性值后,元素会固定在网页的某个位置。

<html><head>   <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">   <title>position</title>   <style>      div{         border:solid 1px #aaa;         width:200px;         height:200px;         position: fixed;         top:105px;         left:200px;         background: #000;      }   </style></head><body><div>我是一个盒子,我用的是固定定位</div></body></html>

效果图:

·

(3)relative 相对定位:元素相对于自身所在位置进行定位,但是并不会影响在其后的元素的位置。

<head>   <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">   <title>relative</title>   <style>      body{         background: #aaa;      }      div{         border:solid 1px #aaa;         width:200px;         height:200px;         position: relative;         top:105px;         left:200px;         background: #000;         color:#fff;      }      div>div{         border:solid 1px #aaa;         width:100px;         height:100px;         position: relative;         top:65px;         left:80px;         background: #ab18ff;         color: #000000;      }   </style>   </head><body><div>   我是爸爸   <div class="son">      我是儿子   </div></div></body></html>

效果图:

(4)absolute 绝对定位  :绝对定位是有参照物的,这个参照物就是父容器,并且父容器要设置相对定位,如果没有设置相对定位,就继续寻找父容器的上一级父容器,以此类推,直到找到设置了相对定位的父元素,若都没有,则以<body>为参照物,元素进行绝对定位后,会影响其后元素的位置。

<html><head>   <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">   <title>position</title>   <style>      div{         border:solid 1px #aaa;         width:200px;         height:200px;         position: relative;         top:105px;         left:200px;         background: #000;         color:#fff;      }      div>div{         border:solid 1px #aaa;         width:100px;         height:100px;         position: absolute;         top:65px;         left:60px;         background: #f76e07;      }   </style></head><body><div>   我是一个盒子,我用的是相对定位定位   <div class="son">      我是一个盒子,我用的是绝对定位   </div></div></body></html>

效果图:

 

 

原创粉丝点击