欢迎光临散文网 会员登陆 & 注册

CSS中浮动和定位有什么区别?

2023-05-04 09:42 作者:云和数据何老师  | 我要投稿

其实浮动的本意是用来解决图片和文字的排版问题,但是由于它十分好用,所以被大部分开发者应用到了网页布局中,并成为了公认布局的一种方式。

接下来,我们通过一个demo演示一下浮动和定位在网页布局中的使用,如demo1所示。

<!DOCTYPE html><html lang""en"> <head><meta charset="UTF-8"><title>浮动和定位</title></head><style type="text/css">    /*给类名为header、aside、main、footer的元素设置背景颜色和边框*/    .header, .aside, .main, .footer {    background-color:pink/*背景色为粉色*/    border: lpx solid yellow; /·边框为1px 的黄色实线*/    }    , header {    height: 100px;    }    .aside, .main {    height: 200px;    }    .aside {      width: 200px;      float:left; /*类名为aside的元素左浮动*/    }    .main {      margin-left:202px;    /*元素左边距为202px*/  }  .footer {    height: 50px:  }  /*给类名为hpat-div的元素设置背景颜色、边框、宽高及绝对定位*/  .float-div {    background-color: paleturquoise; /*背景色为苍白的宝石绿*/    border:lpx solid yellow; /·边糕为lpx的黄色实线*/    width: 100px;    height: 100px;    position: absolute: /*绝对定位*/    top:160px; /*距父元素顶部边线160px*/    left:500px; /*距父元素左边线500px*/}</style> <body>   <header class="header">header</header>   <aside class="aside">aside</aside>   <section class="main">section</section>   <footer class="footer">footer</footer>   <div class="float-div">floatdiv</div> </body> </html>

用浏监器打开demo1.页面效果如图。

 

在demo1中,使用浮动的知识对页面进行了布局,也就是图1-13中的header、aside、section、footer区域,然后使用绝对定位知识创建了一个浮动的div元素floatdiv。需要注意的是,position:absolute会导致元素脱离文档流,被定位的元素等于在文档中不占据任何位置,在另一个层呈现。float也会导致元素脱离文档流,但还在文档或容器中占据位置,把文档流和其他float元素向左或向右挤,并可能导致换行。


CSS中浮动和定位有什么区别?的评论 (共 条)

分享到微博请遵守国家法律