【发布时间】:2023-03-22 12:12:01
【问题描述】:
我有一个位置相对的 div,这个 div 有几个绝对位置的子元素。 每个孩子都有很少的元素并显示弹性列。它们的大小可以不同,因为每个孩子的内容都不相同。 如何扩展父 div 的高度以完全适合所有孩子的高度?
如果您查看检查元素,您会看到父 div 采用宽度来适应内容,而不是高度。
(所以基本上我希望班级团队的 div 高度不为 0,但我不能给它一个固定的高度)
.teamate {
position: absolute;
width: 40%;
display: inline-flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.teamate .sub-line {
width: 25%;
}
.teamate img {
width: 55%;
}
.teamate p {
width: 50%;
}
.team {
position: relative;
}
<div class="team">
<div class='teamate'>
<img src="style/img/leftphoto.png" alt="">
<h1>FIRST TEAMATE</h1>
<h2>ROLE AND POSITION</h2>
<img class="sub-line" src="style/img/subline.png">
<p>
Long description about teamate. Long description about teamate.
Long description about teamate. Long description about teamate.
Long description about teamate. Long description about teamate.
</p>
</div>
<div class='teamate'>
<img src="style/img/leftphoto.png" alt="">
<h1>FIRST TEAMATE</h1>
<h2>ROLE AND POSITION</h2>
<img class="sub-line" src="style/img/subline.png">
<p>
Long description about teamate. Long description about teamate.
Long description about teamate. Long description about teamate.
Long description about teamate. Long description about teamate.
</p>
</div>
<div class='teamate'>
<img src="style/img/leftphoto.png" alt="">
<h1>FIRST TEAMATE</h1>
<h2>ROLE AND POSITION</h2>
<img class="sub-line" src="style/img/subline.png">
<p>
Long description about teamate. Long description about teamate.
Long description about teamate. Long description about teamate.
Long description about teamate. Long description about teamate.
</p>
</div>
<div class='teamate'>
<img src="style/img/leftphoto.png" alt="">
<h1>FIRST TEAMATE</h1>
<h2>ROLE AND POSITION</h2>
<img class="sub-line" src="style/img/subline.png">
<p>
Long description about teamate. Long description about teamate.
Long description about teamate. Long description about teamate.
Long description about teamate. Long description about teamate.
</p>
</div>
</div>
【问题讨论】:
-
你不能。绝对子代不考虑相对父代的尺寸。我建议你重新考虑你的布局方法。
-
不清楚你想要达到什么效果。你有建议结果的图片吗?
-
这是我想做的结果图片:ibb.co/Lg0xZtk
-
如您所见,我需要右侧的两项比左侧的两项更位于页面下方,我认为相对和绝对可能是一个不错的选择,但显然所有否决票我认为我错了 lmao
-
不要使用相对定位和绝对定位,因为它会反应迟钝,而且处理起来很乱。最简单的方法是使用带有 flexbox 或网格的 2 列布局。使用
nth-child伪选择器将右列移到下面。我对 css-grid 解决方案的 anwser 展示了您如何做到这一点。