当子元素具有可变高度时,是否可以将子元素的底部与父元素的顶部对齐(使用纯CSS/SASS)强>?我想实现一个位于父级上方(Y 轴)的弹出窗口。
<div id="parent">
<div id="child">
Bottom border of this should always be on top
border of parent - regardless of child's height
</div>
</div>
我可以使用 position:absolute
和 top: someOffset
将子项相对于 relative
父项进行偏移,但这需要在 js 中进行动态偏移计算(我不知道如何使用 calc() 来做到这一点)或固定子高度,但是当子物体改变高度时,它会溢出父物体或在它们之间留下间隙。
最佳答案
有两种方法可以解决这个问题:
#parent {
display: inline-block;
width: 180px;
height: 100px;
margin: 100px 0;
border: 1px solid red;
position: relative;
}
.child {
position: absolute;
border: 1px solid green;
}
.one {
bottom: 100%;
}
.two {
top: 0;
transform: translateY(-100%);
}
/* this one is hacky but can be useful in some cases */
.three {
height: 0;
top: 0;
display: flex;
align-items: flex-end;
}
<div id="parent">
<div class="child one">
Bottom border of this should always be on top border of parent - regardless of child's height
</div>
</div>
<div id="parent">
<div class="child two">
Bottom border of this should always be on top border of parent - regardless of child's height
</div>
</div>
<div id="parent">
<div class="child three">
Bottom border of this should always be on top border of parent - regardless of child's height
</div>
</div>
关于CSS:当子元素的高度可变时,将子元素的底部与父元素的顶部(Y 轴上方)对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60921692/