天天看點

position:fixed;

為什麼設定position:fixed;div會消失。

此文如有不正确的地方,敬請留言指出,謝謝。

1.position:fixed;作用

生成絕對定位的元素, 相對于浏覽器視窗進行定位。可以通過設定 "left", "top", "right" 以及 "bottom" 屬性給目标元素定位。 例如:将id = content 的div固定在視窗底部,距離視窗左邊距離200px。滾動條上下滾動,div仍然在視窗底部。

<style>
        html,body,div{
            margin: 0;
            padding: 0;
        }
        body{
            height: 1200px;
        }
        #content{
            width: 400px;
            height: 50px;
            background: dimgrey;
            position: fixed;
            bottom: 0px;
            left: 200px;
        }
    </style>
</head>
<body>
    <div id="content">I am content!</div>
</body>
           
position:fixed;

2.當頁面沒用滾動條時,不設定 "left", "top", "right" 以及 "bottom" 屬性時,頁面排版後,目标div位于父級除去margin,padding後的最頂最左處。但此時的"left", "top", "right" 以及 "bottom" 屬性仍然是根據浏覽器視窗取值。

<style>
        html,body,div{
            margin: 0;
            padding: 0;
        }
        #box{
            margin: 20px;
            padding: 20px;
            height: 60px;
            border:1px solid darkred;
        }
        #content{
            position: fixed;
        }
    </style>
</head>
<body>
<div id="box">
    <div id="content">I am content!</div>
</div>
<script type="text/javascript" src="jquery-3.2.1.slim.min.js"></script>
<script>
    console.log("content top is ",$("#content").css("top"));
    console.log("content left is ",$("#content").css("left"));
</script>
</body>
           
position:fixed;

3.當頁面有滾動條時,不設定"left", "top", "right" 以及 "bottom" 屬性時,頁面排版後,目标元素“莫名其妙”消失。原因:元素的"left", "top", "right" 以及 "bottom" 屬性仍然是根據浏覽器視窗取值。

<style>
        html,body,div{
            margin: 0;
            padding: 0;
        }
        #content{
            position: fixed;
        }
    </style>
</head>
<body>
<div id="headerBox" style="height: 1200px; border:1px solid red;">I am headerBox!</div>
<div id="box" style="margin: 20px;padding: 20px;height: 60px;border:1px solid darkred;">
    <div id="content">I am content!</div>
</div>
<script type="text/javascript" src="jquery-3.2.1.slim.min.js"></script>
<script>
    console.log("content top is ",$("#content").css("top"));
    console.log("content bottom is ",$("#content").css("bottom"));
</script>
</body>
           
position:fixed;

此時看一下控制台,content div的top,bottom值

position:fixed;

綜上所述,不是div消失,隻是相對于視窗而取值的top,left,right,bottom,讓div沒有出現在視窗上。運用position:fixed;一定要抱緊“ 相對于浏覽器視窗"進行定位這個條件!

繼續閱讀