CSS:当子元素的高度可变时,将子元素的底部与父元素的顶部(Y 轴上方)对齐

标签 css sass

当子元素具有可变高度时,是否可以将子元素的底部与父元素的顶部对齐(使用纯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:absolutetop: 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/

相关文章:

javascript - 我可以告诉一个 div 使用另一个 div 中的图像吗? CSS JS

javascript - 如何使用 CSS(较少)

html - 父容器不随高度属性增长

sass - 未定义操作 : "-zf-bp-to-em(0) gt 0em" when compiling foundation

css - 风格化 Sencha Touch 应用程序的最佳方式是什么?

ruby - 语法错误 : File to import not found or unreadable: compass/css3

iphone - 通过 Javascript 增加 SO 字体大小在我的 iPhone 上不起作用

html - 阻止背景在固定宽度布局上调整为视口(viewport)大小

css - 模态框需要贴在屏幕右侧

ruby-on-rails - 分析开发中的缓慢 Assets