注:默认情况下的定位是 postion:static;

  • 使用定位时,常常使用偏移量对位置进行描述:left、right、top、bottom
  • 定位时,使用z-indent可以元素的堆叠顺序,例:z-indent:1,出现在上层(z-index 仅能在定位元素上奏效

相对定位relative

相对定位的参考物是元素的初使位置

相对定位的特点:

  • 不影响元素本身的特性
  • 元素不脱离文档流
  • 相对于原位置进行偏移
        div{
            width: 100px;
            height: 100px;
            margin: 10px;
            font-size: 40px;
            text-align: center;
            line-height: 100px;
            background-color: orange;
        }
        div:nth-of-type(2){
            position: relative;
            left: 100px;
        }
        <div>1</div>
        <div>2</div>
        <div>3</div>

相对定位relative、绝对定位absolute、固定定位fixed


绝对定位absolute 

绝对定位的参考物是:距离最近的使用了定位的父级,父级都没有使用时找body

绝对定位的特点:

  •  元素脱离文档流
  • 行元素支持所有的css样式
  • 块元素由内容撑开宽高
  • 清除子级浮动
        div{
            width: 100px;
            height: 100px;
            margin-bottom: 10px;
            font-size: 40px;
            text-align: center;
            line-height: 100px;
            background-color: orange;
        }
        div:nth-of-type(2){
            position: absolute;
            left: 100px;
        }
        <div>1</div>
        <div>2</div>
        <div>3</div>

相对定位relative、绝对定位absolute、固定定位fixed

        .one{
            background-color: orange;
            width: 300px;
            height: 300px;
            position: relative;
        }
        .two{
            background-color: greenyellow;
            width: 200px;
            height: 200px;
            position: absolute;
            top: 50px;
            left: 50px;
        }
        .three{
            background-color: skyblue;
            width: 100px;
            height: 100px;
            position: absolute;
            top: 50px;
            left: 50px;
        }
        <div class="one">
            <div class="two">
                <div class="three"></div>
            </div>
        </div>

相对定位relative、绝对定位absolute、固定定位fixed

 使用定位实现万能居中:

        .background{
            width: 100vw;
            height: 100vh;
            background-color: rgba(0, 0, 0, .7);
        }
        .background div{
            width: 300px;
            height: 200px;
            background-color: #fff;
            /* 以下代码实现万能居中 */
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -150px;
            margin-top: -100px;
        }
        <div class="background">
            <div>
                万能居中公式:<br>
                position: absolute;<br>
                left: 50%;<br>
                top: 50%;<br>
                margin-left: -width/2;<br>
                margin-top: -height/2;<br>
            </div>
        </div>

相对定位relative、绝对定位absolute、固定定位fixed


固定定位fixed

参考物:浏览器窗口

固定定位的特点: 

  • 脱离文档流
  • 清除子级浮动

固定定位的实现 可以使页面中的某个元素不随浏览器的滚动而消失,例如 导航栏的固定实现

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。