5月21日

网页定位 4 种方式
一、四种定位属性
position: static; /* 默认静态定位 /
position: relative; /
相对定位 /
position: absolute; /
绝对定位 /
position: fixed; /
固定定位 */

  1. static 静态定位(默认)
    正常文档流,正常排版
    top/left/right/bottom/z-index 全都无效
    几乎不用写,默认就是它
  2. relative 相对定位
    特点
    相对于自己原来的位置移动
    不脱离文档流,原来位置还占着
    常用:微调位置、给绝对定位当父级参照物
    用法
    .box{
    position: relative;
    top: 20px; /* 向下移20 /
    left: 30px; /
    向右移30 */
    }
  3. absolute 绝对定位(最常用)
    核心口诀:
    父相子绝 → 父 relative,子 absolute
    规则
    脱离文档流,不占位置
    找最近一层有定位的父元素做参照物
    父无定位 → 参照物是浏览器可视区
    标准用法
    /* 父盒子 /
    .father{
    position: relative;
    }
    /
    子盒子 */
    .son{
    position: absolute;
    top: 0;
    right: 0;
    }
  4. fixed 固定定位
    参照物:浏览器窗口
    脱离文档流,滚动页面位置不变
    常用于:顶部导航、回到顶部、侧边悬浮按钮
    .back-top{
    position: fixed;
    right: 30px;
    bottom: 50px;
    }
    定位常用搭配
    居中定位
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    盒子放右上角
    父相对 + 子绝对:top:0; right:0
    悬浮按钮:直接 fixed
    优先级
    定位 > 浮动 > 标准流
    z-index 控制层级,只对定位元素生效
    速记总结
    自己挪位置:relative
    放盒子里面任意位置:父相子绝 absolute
    跟着屏幕不动:fixed
    正常布局不动:默认 static
posted @ 2026-07-06 11:15  +6  阅读(7)  评论(0)    收藏  举报