Web开发中常用的定位布局position

来源:互联网 发布:四川网络电视台 编辑:程序博客网 时间:2024/06/05 07:48

定位布局就是为开发提供了更好的布局方式,可以根据需求给相应的模块设定相应位置,从而使界面更佳丰富,代码更佳完美。

position是CSS中非常重要的一个属性,通过position属性,我们可以让元素相对于其正常位置,父元素或者浏览器窗口进行偏移。

 

position 属性,它有4个不同类型的定位,这些类型会影响元素的生成方式,下面我们详细说明position属性。

static 定位

是静态定位,是position的默认值,元素出现在正常的流中(正常布局),静态定位的元素不会受到 top, bottom, left, right影响。


fixed 定位

absolute一致,但定位是以窗口为参考。当出现滚动条时,对象不会随着滚动,相当于位置设置之后,以浏览器未参考,他是不会改变的,可用于做界面广告(我们浏览网页是的广告,大多数都在一个位置)。


relative 定位

相对定位,他是默认参照父级的原始点为参考点,通过top,left,bottom,right这4个定位偏移属性进行偏移,不会影响常规流中的任何元素。


absolute 定位

绝对定位的元素的位置相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于最初的包含块

 

通过案例介绍其四个属性,效果如图:

           

 

代码:

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title>position</title>    </head>    <style type="text/css">        *{margin: 0px 0px;padding: 0px 0px;}                .header{            height:95px;            background: green;        }                .main{            height: 255px;            background: wheat;        }                p{            position: static;/*不会受到 top, bottom, left, right影响*/            top: 11px;/*设置了没影响*/        }                .three{            width: 155px;            height: 155px;            position: fixed;/*固定定位相对于父div 如广告在上面一样*/            right: 16px;            top: 155px;            background-color: green;            z-index: 2;/*层的覆盖关系值越高越在上面*/        }                /*相对父级div   class=main来布局(没有则按照  body来布局)*/        .one{            position: relative;            width: 199px;            height: 115px;            top: 25px;            left: 25px;            background: red;            color: white;        }        /*相当于浏览器窗口来布局*/        .tow{            position: absolute;            width: 196px;            height: 55px;            top: 15px;            left: 55px;            background: gold;        }                h1{            margin-bottom: 25px;        }            </style>    <body>        <div class="header">            header        </div>        <p>static   正常布局  没有其他影响</p>        <div class="main">            <div class="one">我是relative 相对布局  相对父级div   class=main来布局(没有则按照  body来布局)</div>            <div class="tow">我是absolute  绝对布局 相当于浏览器窗口来布局</div>            <div class="three">fixed:我是广告,我永远不会动,拖滚动条我也不动</div>        </div>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>        <h1>我是文本</h1>    </body></html>

通过以上代码,可以是你更方便,更容易的学习CSS的position属性,希望对你有所帮助。

 


原创粉丝点击