詳解如何解決position:fixed固定定位偏移問(wèn)題
問(wèn)題
css固定定位position:fixed很容易使用,就是相對(duì)瀏覽器的viewport進(jìn)行定位,top:0;left:0就是在左上角。
<body>
<div class="container">
</div>
</body>
<style>
.container{
width: 100px;
height: 100px;
background: #888;
position: fixed;
top: 100px;
left: 100px;
}
</style>

當(dāng)父級(jí)元素設(shè)置transform之后
<body>
<div class="BFC-box">
<div class="container"></div>
</div>
</body>
<style>
.BFC-box{
margin:200px;
height: 200px;
width: 200px;
border:2px solid red;
transform: scale(1);
}
.container{
width: 100px;
height: 100px;
background: #888;
position: fixed;
top: 100px;
left: 100px;
}
</style>
fixed元素變成了相對(duì)父元素進(jìn)行定位。

真是令人蛋疼,原因在于transform提升了元素的地位,在W3C規(guī)范中有如下說(shuō)明:
For elements whose layout is governed by the CSS box model, any value other than none for the transform also causes the element to become a containing block, and the object acts as a containing block for fixed positioned descendants
在transform不為none的元素中,定位是會(huì)受到影響的。
解決方案
在不影響布局的情況下,可以直接把要定位的元素移動(dòng)到body下:
<body> <div class="BFC-box"></div> <div class="container"> </div> </body>
如果是在組件中不方便對(duì)元素進(jìn)行操作,可以使用js,以vue為例:
<div ref="container" class="container"></div>
mounted(){
document.body.append(this.$refs['contaier'])
}
到此這篇關(guān)于詳解如何解決position:fixed固定定位偏移問(wèn)題的文章就介紹到這了,更多相關(guān)position:fixed固定定位偏移內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!
相關(guān)文章

CSS 同級(jí)元素position:fixed和margin-top共同使用的問(wèn)題
這篇文章主要介紹了CSS 同級(jí)元素position:fixed和margin-top共同使用的問(wèn)題的相關(guān)資料,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-09-13css中position:fixed實(shí)現(xiàn)div在窗口上下左右居中
實(shí)現(xiàn)div居中的方法有很多,本例介紹的使用css中position:fixed來(lái)實(shí)現(xiàn)div的上下左右居中,下面以一個(gè)DIV 元素在瀏覽器窗口居中為例2014-10-20css中position:fixed實(shí)現(xiàn)div居中上下左右居中
實(shí)現(xiàn)div居中的方法多如牛毛,本例為大家介紹的這個(gè)方法是使用css中position:fixed來(lái)實(shí)現(xiàn)div上下左右居中,這個(gè)小技巧比較使用,大家看看2014-10-14position:fixed或absolute時(shí)百分比參考屏幕寬度
用百分比設(shè)定元素的寬度,一般情況是指參考父元素的寬度,當(dāng)position是fixed或absolute時(shí),百分比是參考屏幕的寬度2014-02-19- 下面與大家分享下使用position:fixed屬性讓DIV居中的關(guān)鍵代碼是position:fixed;left:0px;right:0px;width:706px;margin-left:auto;margin-right:auto,感興趣的朋友可以參2013-05-15
ie6下實(shí)現(xiàn)position:fixed效果實(shí)例介紹
由于IE6并不支持position:fixed,所以導(dǎo)致很多好的效果都無(wú)法實(shí)現(xiàn),但是在IE6下并不是不能夠?qū)崿F(xiàn),下面就通過(guò)一段實(shí)例介紹一下如何實(shí)現(xiàn)此種效果;建議:盡可能的手寫代碼,2013-02-16IE6 position:fixed bug (固定窗口方法)
今天herb同學(xué)在twitter上問(wèn)到,如何利用CSS使搜索條固定顯示于窗口的某個(gè)位置。好像之前也碰過(guò)這個(gè)問(wèn)題,不過(guò),當(dāng)時(shí)并沒(méi)有解決,用JS有現(xiàn)成的方法,不過(guò),這次要求的就是不2011-04-26- 當(dāng)前主流瀏覽器中,chrome,firefox,ie7,8等想要固定一個(gè)元素位置,不隨內(nèi)容的滾動(dòng)而滾動(dòng),眾所周知,css中position: fixed;即可解決。2010-09-21
- 在IE6.0及以下版本的瀏覽器里是不支持position:fixed。而在IE7,IE8,firefox,opera,chrome都可以完美的支持此特性的。2010-06-01
IE7下當(dāng)position:fixed遇到text-align:center的解決方法
IE7下當(dāng)position:fixed遇到text-align:center 的一些狀況,大家可以參考下。2010-03-05


