2016-11-22 110 views
1

我對定位元素有一個討厭的問題: 所以我有一個孩子,需要有全屏寬度,而不是相對父母的。設置相對父寬度較小時的絕對元素全寬度爲100%

body{ 
 
    padding: 10px; 
 
} 
 
.container{ 
 
    position:relative; 
 
    width: 400px; 
 
    border: 1px solid red; 
 
    padding: 15px; 
 
} 
 
.panel{ 
 
    position:relative; 
 
    width:200px; 
 
    margin: 0 auto; 
 
    height:40px; 
 
} 
 
.panel-body{ 
 
    position: absolute; 
 
    width:100%; 
 
}
<div class="container"> 
 
    <div class="panel panel-warning"> 
 
    <div class="panel-body"> 
 
     A Basic Panel 
 
    </div> 
 
    </div> 
 
</div>

所以問題是如何使panel-body中的所有其他元素的前面,並從屏幕不從父相對設置寬度100%,但是100%。 The html structure cannot be modified.

fiddle:

+0

'如何將面板主體放在所有其他元素前面,請使用[css z-index](http://www.w3schools.com/cssref/pr_pos_z-index.asp)。至於使一個孩子比它的父母檢查更廣泛[this](http://stackoverflow.com/questions/5581034/is-there-are-way-to-make-a-child-divs-width-wider-than -the-parent-div-using-css)鏈接。 –

+1

你可以在'.panel-body'上設置'position:fixed'而不是'absolute'。 –

+1

@MuhammadUsman這將工作,直到你必須滾動 – Keith

回答

2

這似乎工作,我想我僥倖它雖然。

body{ 
 
    padding: 10px; 
 
} 
 
.container{ 
 
    position:relative; 
 
    width: 400px; 
 
    border: 1px solid red; 
 
    padding: 15px; 
 
} 
 
.panel{ 
 
    position:relative; 
 
    width:200px; 
 
    margin: 0 auto; 
 
    height:40px; 
 
} 
 
.panel-body{ 
 
    position: absolute; 
 
    margin-left: calc(-50% - 20px - 15px); 
 
    width:100vw; 
 
    background-color: yellow; 
 
}
<div class="container"> 
 
    <div class="panel panel-warning"> 
 
    <div class="panel-body"> 
 
     A Basic Panel 
 
    </div> 
 
    </div> 
 
</div>

+1

不錯,我忘了'vw'! – Pete

+0

@Keith其實這是一個非常好的主意:) ty – BurebistaRuler

+1

沒有probs。僥倖的位是20px,我可以理解它是10px,但考慮到它,我認爲身體有一個默認的10px的邊距,所以這可能是額外的10px來自...因此,'body-margin + body-填充+容器填充= 10px + 10px + 15px'。最終='-50%-35px' – Keith

1

如果我沒有理解問題...

您需要定義左邊距和利潤率上到所有家長的負和值offsetLeft和機頂盒簡單瞭如果所有父母都將位置轉換爲負數和。

function getOffsetLeft(elem) 
{ 
    var offsetLeft = 0; 
    do { 
     if (!isNaN(elem.offsetLeft)) 
     { 
      offsetLeft += elem.offsetLeft; 
     } 
    } while(elem = elem.offsetParent); 
    return offsetLeft; 
} 

我找到了一些答案您:

finding element's position relative to the document

現在你知道你的立場,這是很容易設置的元素位置類型絕對新的位置。

你想要某種全屏。將x位置設置爲 - (sumOfOffsetLeft) 也適用於y。

對於寬度100%,不需要計算,只需使用window.innerWidth也許是 window.innerWidth/100 * 95(屏幕的95%)。

相關問題