css定位

116 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第6天,点击查看活动详情

一。 position的定位分类

①。static 默认值,没有定位

②。relative 相对定位

相对自身原来位置进行偏移 ,偏移设置:top、left、right、bottom ,盒子移动的(0,0)点在左上角 ,置相对定位的盒子仍在标准文档流中,它对父级盒子和相邻的盒子都没有任何影响 设置相对定位的盒子原来的位置会被保留下来

1.png

  *{
     margin: 0;padding: 0;
 }
 .box{
     width: 300px;
     height: 200px;
     border: 2px solid #ccc;
 }
 .a{
     width: 200px;
     height: 50px;
     background-color: red;
    margin: 15px 20px;
 }
 .b{
     width: 200px;
     height: 50px;
     background-color: yellow;
   margin-left: 20px;
     position: relative;
     left: 20px;
     top:30px;
     相对原来的位置距离左边远了20PX,距离上边远了30PX}

 .c{
     width: 200px;
     height: 50px;
     background-color:blue;
     margin: 15px 20px;
 }

相对原来的位置距离左边远了20PX,距离上边远了30PX

2.png ③。absolute 绝对定位

使用了绝对定位的元素以它最近的一个“已经定位”的“祖先元素”为基准进行偏移,建议为基准的的祖先元素定位使用 相对定位,因为相对定位不会让父级脱离文档流 而absolute和fixed会脱离文档流。

4.png

          *{
             margin: 0;padding: 0;
 }
 .box{
     width: 300px;
     height: 200px;
     border: 2px solid #ccc;
     position: relative;
 }
 .a{
     width: 200px;
     height: 50px;
     background-color: red;
    margin: 15px 20px;
 }
 .b{
     width: 200px;
     height: 50px;
     background-color: yellow;
     margin-left: 20px;
     position: absolute;
     right: 100px;
     /* 以父辈.box为基准,距离右边100PX,距离 上边50PX */
    top: 50px;
 }
 .c{
     width: 200px;
     height: 50px;
     background-color:blue;
     margin: 15px 20px;
 }如果没有已经定位的祖先元素,会以浏览器窗口为基准进行定位
 

5.png ④。fixed 固定定位

偏移设置: left、right、top、bottom 类似绝对定位,不过区别在于定位的基准不是祖先元素,而是浏览器窗口,一般在网页中被用在窗口左右两边的固定广告、返回顶部图标、吸顶导航栏等

6.png

    * {
        margin: 0;
        padding: 0;
    }

    .box {
        width: 500px;
        height: 1500px;
        border: 5px solid yellow;
        position: relative;
        margin: 0 auto;
    }

    .a {
        width: 200px;
        line-height: 200px;
        background-color: aqua;
        text-align: center;
        position: absolute;
        /* absolute根据最亲近的长辈来定位的,如果所有长辈都没设置定位,就根据浏览器窗口视角定位 */
        left: 100px;
        top: 50px;
    }

    .b {
        width: 200px;
        line-height: 200px;
        background-color: red;
        text-align: center;
        position: fixed;
        /* fixed是根据浏览器窗口视角定位的,不受下拉框的限制,始终固定在那个位置 */
        right: 100px;
        top: 200px;
    }

7.png