CSS基础<五>定位与精灵图

作者: 大基本功 | 来源:发表于2017-12-04 16:15 被阅读245次
1.静态定位
  • position:static;
  • 定位的默认值,文档流
2.绝对定位
  • position:absolute;
  • 特点
    • 元素使用绝对定位之后处于脱标不占据原来的位置
    • 元素使用绝对定位,位置是从浏览器出发
    • 嵌套的盒子,父盒子没有使用定位,子盒子绝对定位,子盒子位置是从浏览器出发
    • 嵌套的盒子,父盒子使用定位,子盒子绝对定位,子盒子位置是从父元素位置出发
      <head>
      <meta charset="UTF-8">
      <title>Document</title>
      <style type="text/css">
          body,div{
              margin: 0;
              padding: 0;
          }
          .big{
      
              margin: 20px;
              background-color: beige;
              width: 100px;
              height: 100px;
              /*position: absolute;*/给父盒子相对定位
              /*top: 50px;*/
              /*left: 50px;*/
          }
          .small{
              position: absolute;
              background-color: cadetblue;
              width: 50px;
              height: 50px;
              top: 10px;
              left: 10px;
          }
      </style>
      </head>
      <body>
       <div class="big">
           <div class="small"></div>
       </div>
      </body>
      
image.png
  • 当一个盒子绝对定位之后不能使用margin: 0 auto;让盒子自身居中
    如果想让过一个绝对定位的盒子自身居中, 可以使用left: 50%; margin-left:-元素宽度一半px;
3.相对定位
  • position:relative;
  • 特点
    • 位置从自身定位前在标准流中的位置出发
    • 还占据原来的位置
  • 父元素相对定位,子元素绝对定位
    • 开发中一般采用父元素使用相对定位子元素使用绝对定位配合使用进行定位
4.固定定位
  • position:fixed;
  • 特点:
    • 固定定位之后,不占据原来的位置(脱标)
    • 元素使用固定定位之后,位置从浏览器出发。
    • 元素使用固定定位之后,会转化为行内块(不推荐,推荐使用display:inline-block;)
5.z-index属性
  • 用于指定定位的元素的覆盖关系
  • 定位元素的覆盖关系
    • 默认情况下定位的元素一定会盖住没有定位的元素
    • 默认情况下写在后面的定位元素会盖住前面的定位元素
    • 默认情况下所有元素的z-index值都是0, 如果设置了元素的z-index值, 那么谁比较大谁就显示在前面
  • 定位元素的从父现象
    • 父元素没有z-index值, 那么子元素谁的z-index大谁盖住谁
    • 父元素z-index值不一样, 那么父元素谁的z-index大谁盖住谁
6.精灵图
  • 全称CSS Sprite,很多网页中的小图标组成的一张图
  • 通过background-position移动图片并截取所需部分
sprite.png
 <style>
        .box{
            width: 50px;
            height: 50px;
            background-image: url(images/sprite.png);
            background-position: -50px -50px;
        }
  </style>

相关文章

网友评论

    本文标题:CSS基础<五>定位与精灵图

    本文链接:https://www.haomeiwen.com/subject/mjwtixtx.html