[英]Adapt parent to maximum size of it's children in CSS
是否可以讓父div將其高度調整為孩子的最大高度,將寬度調整為孩子的寬度的最大寬度?
* { box-sizing: content-box; } .parent { position: relative; border: 2px solid blue; height: max-content; width: max-content; } .child-a { position: relative; background: rgba(255, 0, 0, 0.3); width: 135px; height: 100px; top: 0; left: 0; } .child-b { position: absolute; background: rgba(0, 255, 0, 0.3); width: 100px; height: 135px; top: 0; left: 0; }
<div class='parent'> <div class='child-a' /> <div class='child-b' /> </div>
在上面的示例中,我嘗試了position,top,left屬性的各種組合。
也許有可能至少在一個維度上實現這種效果?
是的, 沒有 position:absolute
就可以實現position:absolute
使用CSS-Grid並在同一網格單元中對元素進行分層。
* { box-sizing: content-box; } .parent { position: relative; border: 2px solid blue; height: max-content; width: max-content; display: grid; } .child-a { position: relative; background: rgba(255, 0, 0, 0.3); width: 135px; height: 100px; grid-column: 1 / -1; grid-row: 1; } .child-b { background: rgba(0, 255, 0, 0.3); width: 100px; height: 135px; grid-column: 1 / -1; grid-row: 1 }
<div class='parent'> <div class='child-a'></div> <div class='child-b'></div> </div>
如果您想要比CSS網格更好的支持,則可以使用簡單的float來完成
* { box-sizing: content-box; } .parent { display:inline-block; /* This */ border: 2px solid blue; } .child-a { background: rgba(255, 0, 0, 0.3); float:left; /* and this */ width: 135px; height: 100px; } .child-b { background: rgba(0, 255, 0, 0.3); width: 100px; height: 135px; } /* To illustrate that it works whataver the width/height */ .parent:hover .child-b{ width:180px; } .parent:hover .child-a{ height:180px; }
<div class='parent'> <div class='child-a' ></div> <div class='child-b' ></div> </div>
是的,我們可以通過CSS網格實現這一目標。
* { box-sizing: content-box; } .parent { display: grid; grid-template-areas: "grid-overlap"; border: 2px solid blue; height: auto; width: max-content; } .child-a { grid-area: grid-overlap; background: rgba(255, 0, 0, 0.3); width: 135px; height: 100px; overflow: overlay; } .child-b { grid-area: grid-overlap; background: rgba(0, 255, 0, 0.3); width: 100px; height: 135px; }
<div class='parent'> <div class='child-a'></div> <div class='child-b'></div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.