栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > Html/CSS > CSS教程

position: absolute 值得注意的地方

CSS教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

position: absolute 值得注意的地方

absolute 的特性

与 float 相比,两者都具有包裹性、块化性和破坏性。
在破坏性上,两者略有不同,absolute 是完全不占据文档流空间的,并且如果两者同时存在时,float 不起作用。

例子:


    div {
 overflow: hidden;
 outline: auto;
    }
    
    p {
 background-color: coral;
 width: 50px;
 height: 50px;
 float: left;
 margin: 5px;
 color: white;
    }
    
    p:first-child {
 background-color: cadetblue;
    }
    
    p:nth-child(2) {
 position: absolute;
 top: 20px;
 left: 130px;
    }
    
    p:last-child {
 background-color: darkgoldenrod
    }



    

1

2

3

相关内容可以参考:
float 的本质
float 的包裹性与块化性

absolute 的初始位置

一个具有 absolute 属性的元素,如果没有任何定位设置,其初始位置就是当前位置。可能很多人误认为是其包含块的左上角,实际并非这样。

例子:


    div {
 background-color: #eee;
 position: relative;
 margin-bottom: 10px;
    }
    
    div label {
 color: #fff;
    }
    
    div:first-child>label {
 background-color: cadetblue;
    }
    
    div:last-child>label {
 background-color: darkgoldenrod
    }
    
    div:first-child>label+span,
    div:last-child>label+nav {
 position: absolute;
    }



    span


    
    

absolute 的这一特点,非常适合小图标的设定。

例子:


    ul {
 overflow: hidden;
 margin: 0;
 padding: 0;
    }
    
    ul li {
 float: left;
 list-style: none;
 padding: 0 15px;
    }
    
    i {
 position: absolute;
 color: red;
 font-size: 12px;
 margin-top: -6px;
 margin-left: 2px;
    }


  • 首页
  • 新闻new
  • 热门人物hot

例子中,我们没有设置 absolute 的 left、top 等属性值,而是通过 margin 进行定位,不但完成了既定样式,而且以后导航的文字增减,依然不会影响文字与小图标的相对位置,自适应性非常健壮。

absolute 的特点远远不止上述的这些,更多内容可以参考:
包含块模型
宽度的流动性与包裹性

relative 对 absolute 的限制

relative 就是为了限制 absolute 而生的,虽说 absolute 和 fixed 也有这种限制能力,但 relative 在定位上有其独有的特点。
首先,设置 relative 属性的元素,仍然会保持在标准文档流中,不会影响原来的布局;其次,relative 属性的元素是相对于自身进行定位的( 当前位置即为 left:0 top:0 )。

例子:


    ul {
 float: left;
 margin: 0;
 padding: 0;
    }
    
    ul li {
 background-color: gold;
 float: left;
 list-style: none;
 width: 40px;
 height: 30px;
    }
    
    ul li:first-child {
 background-color: greenyellow;
    }
    
    ul li:last-child {
 background-color: indianred;
    }
    
    ul li:nth-child(2) {
 position: relative;
 top: 10px;
 left: -10px;
    }

  • 1
  • 2
  • 3


如有错误,欢迎指正,本人不胜感激。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/241896.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号