美文网首页
css position属性总结

css position属性总结

作者: 史梦辰 | 来源:发表于2018-12-11 12:38 被阅读0次

    position共有五种不同的定位方法:static,relative,absolute,fixed,sticky

    position:static

    static定位是HTML元素的默认值,即没有定位,元素出现在正常流中,因此这种定位就不受到top,bottom,left,right的影响。
    html:

    <div class="first">
            <div class="second"></div>
        </div>
    

    css:

    .first{
        width:400px;
        height:400px;
        background-color: green;
    }
    .second{
        width:100px;
        height:100px;
        background-color: red;
        position: static;
        top:100px;
        left:100px;
    }
    

    结果:


    image.png

    可以看到,虽然设置了static以及top,left,元素出现在正常流中,并且不受top,left影响。

    position:relative

    相对定位是相对于元素自身的正常位置的偏移,并不会脱离正常流,会在原位置上留下空白。
    html:

    <h1>这里是正常位置的标题</h1>
    <h1 class="pos_top">这里是相对于正常位置向下移动的标题</h1>
    <h1 class="pos_left">这里是相对于正常位置向右移动的位置</h1>
    

    css:

    .pos_top{
        position: relative;
        top:20px;
    }
    .pos_left{
        position: relative;
        left:50px;
    }
    

    结果:


    image.png

    position:absolute

    生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。
    绝对定位的元素相对于于最近的非static祖先元素定位,如果这样的祖先不存在,那么它的位置是相对于<html>的;绝对定位的元素脱离了正常流。
    html:

    <div class="first">
            <div class="second"></div>
        </div>
    

    css:

    .first{
        width:400px;
        height:400px;
        background-color: green;
        position: relative;
    }
    .second{
        width:100px;
        height:100px;
        background-color: red;
        position: absolute;
        top:50%;
        left
    

    结果:


    image.png

    position:absolute常用于元素居中。

    position:fixed

    固定定位是指元素的位置相对于浏览器窗口是固定的,即使窗口是滚动的它也不会滚动,固定定位脱离了正常流,所以它有可能和其他元素发生重叠。


    image.png

    经常用于浏览器中弹出的广告

    position:sticky

    sticky结合了position:relative和position:fixed两种定位的特性。
    元素定位表现为在跨越特定的阈值之前表现为相对定位,在之后为固定定位。
    这个阈值指的是top,left,right,bottom之一,也就是说,必须使用四个阈值之一,才可以使用粘性定位。

    相关文章

      网友评论

          本文标题:css position属性总结

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