[英]DIV 100% width of grandparent while grandparent's width is not 100% viewport
我在這里找到了一些解決方案,但是所有這些解決方案都假定祖父母的電壓為100vw,在我看來,這不是。
這是我想要實現的目標:
<body>
<div id="grandparent" style="width: 1000px">
<div id="parent" style="width: 500px">
<div id="child" style="width: grandparent"></div>
</div>
</div>
</body>
實際上,我需要將孩子的寬度與5級祖父母的寬度對齊。 如果使用純CSS絕對不可能,那么我將感謝JS解決方案。
但是CSS是更可取的。
最接近的解決方案是使子級寬度位置:絕對,將left和right屬性設置為0,然后設置寬度。 不過,這不是CSS中最干凈的事情!
設置position: relative
祖父母的position: relative
和position: absolute
子元素的position: absolute
應該可以解決問題。 但是請記住,祖父母與孩子之間不應有其他相對定位的元素。 考慮下面的代碼:
#grandparent1 {width: 1000px; position: relative; background: yellow;} #grandparent2 {width: 200px; background: pink;} #grandparent3 {width: 300px; background: grey;} #grandparent4 {width: 400px; background: orange;} #grandparent5 {width: 100px; background: aqua;} #parent {width: 500px; background: pink;} #child {width: 100%; background: red; position: absolute;}
<div id="grandparent1"> Grand Parent #1 <div id="grandparent2"> Grand Parent #2 <div id="grandparent3"> Grand Parent #3 <div id="grandparent4"> Grand Parent #4 <div id="grandparent5"> Grand Parent #5 <div id="parent"> Parent <div id="child"> Child </div> </div> </div> </div> </div> </div> </div>
這是僅JavaScript的解決方案(請注意,孩子的寬度在CSS中如何設置為10px,但通過JavaScript重置為1000px以匹配grandparent1的寬度):
document.getElementById('child').style.width = window.getComputedStyle(document.getElementById("grandparent1")).width;
#grandparent1 {width: 1000px; position: relative; background: yellow;} #grandparent2 {width: 200px; background: pink;} #grandparent3 {width: 300px; background: grey;} #grandparent4 {width: 400px; background: orange;} #grandparent5 {width: 100px; background: aqua;} #parent {width: 500px; background: pink;} #child {width: 10px; background: red; position: absolute;}
<div id="grandparent1"> Grand Parent #1 <div id="grandparent2"> Grand Parent #2 <div id="grandparent3"> Grand Parent #3 <div id="grandparent4"> Grand Parent #4 <div id="grandparent5"> Grand Parent #5 <div id="parent"> Parent <div id="child"> Child </div> </div> </div> </div> </div> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.