最近在編碼過程中,遇到過這樣一個問題,代碼如下,我們有一個父級,他有一定的寬度,在他的里面有兩個子級,其中一個是絕對定位的,且要求他們的寬度都和父級保持一致,然后問題就出現了,我們會發現,有了定位的son他的寬度遠遠的超出了我們父級的寬度,那么問題是怎么引起的呢?
<div class="fathor" style="width:1024px"> <div class="son" style="position:fixed;width:100%">
</div>
<div class="demo" style="width:100%">
</div> </div>
經過各種百度之后發現,原來給子元素加了position:fixed這個屬性之后,他就默認相對於window去定位了,就相當與你將這個元素相對於window加上了position:absolute的屬性,所以給他加百分比長度的話就是相對於window的百分比。那么解決方案有哪些呢?我們來一一嘗試。
1、left:0;right:0;因為fixed也相當於是定位的一種,所以我們當然也可以用left和right來進行定位了,然后將left的值擴大,同時將width的百分比減少,從而使得son和demo的寬度達到一致,從而起到一種視覺上的欺騙效果。(PS:請謹慎使用)
<div class="fathor" style="width:1024px;height: 500px;margin: 100px auto;"> <div class="son" style="position:fixed;width: 76%;height: 200px;background-color: darkblue;left: 163px;right: 0;"> </div> <div class="demo" style="width:100%;height: 300px;background-color: red;margin-top: 210px"> </div> </div>
2、calc();關於calc的具體使用將在我后面的播客中提出,在這里,我們可以將son的width由100%改為calc(100%-324px),這里這個長度不知道是否有規律,還是要自己找,相對來說適應性就不是很好。
<div class="fathor" style="width:1024px;height: 500px;margin: 100px auto;"> <div class="son" style="position:fixed;width: calc(100% - 324px);height: 200px;background-color: darkblue"> </div> <div class="demo" style="width:100%;height: 300px;background-color: red;margin-top: 210px"> </div> </div>
3、absolute改造;因為我們上面提到過,本質上說,fixed就是一個相對於window的absolute,但是absolute卻可用relative來指定他相對於誰定位,所以我們在這里,可以將fixed絕對定位用absolute來進行改造。(PS:如果代碼改動不大的情況下建議使用,畢竟更好控制,這種就大家自己操作了喲)
4、給fathor加fixed屬性;我們還可以給fathor加position:fixed;屬性,從而讓父元素也相對於window定位,同時,子元素也是相對於window的定位,所以他們就都是和window產生了聯系,從而也就在一定程度上保持了一致。(PS:這種情況適用於fathor是最外層元素的情況下,否則的話fathor相對於他原來的父級的定位就需要進行重新定義了,而且很大可能會破壞原有樣式)
<div class="fathor" style="width:1024px;height: 500px;margin: 100px auto;transform: scale3d(1, 1, 1);position: fixed;"> <div class="son" style="position:fixed;width: 100%;height: 200px;background-color: darkblue"> </div> <div class="demo" style="width:100%;height: 300px;background-color: red;margin-top: 210px"> </div> </div>