是否可以让父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属性的各种组合。
也许有可能至少在一个维度上达到这种效果?
答案 0 :(得分:3)
是的,使用CSS-Grid并在同一网格单元中对元素进行分层可以不 position:absolute
。
* {
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>
答案 1 :(得分:1)
如果您想要比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>
答案 2 :(得分:0)
是的,我们可以通过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>