首页 > 解决方案 > 在 CSS 中使用位置并计算高度

问题描述

我已将 img 宽度设置为 100%,所以我不知道 img 的高度。我正在尝试使用绝对位置和顶部在 img 的末尾设置一个 div。我们可以使用calc()吗?或者另一种方法。

注意:我已将 img 位置设置为固定。

<div class="container">
<img class="image" src="https://homepages.cae.wisc.edu/~ece533/images/airplane.png">
</div>

<div class="to-image-bottom">I'm div at the bottom of image</div>

标签: htmlcsscss-position

解决方案


您可以使用bottom而不是top定位元素。还使用底部 div 的包装器将其显示在图像之外。例如:

/* Container for image and bottom div */
.container{
  position: relative;
  /* For display content outside of image */
  overflow: visible;
}

/* Image Styles */
.container .image{
  width: 100%;
}

/* Wrapper for bottom div for align to bottom */
.container .to-image-bottom-wrapper{
  position: absolute;
  width: 100%;
  bottom: 0;
}

/* Bottom Div */
.container .to-image-bottom-wrapper .to-image-bottom{
  position: absolute;
  top: 0; /* position relative to wrapper */
  width: 100%;
  background: red;
  color: white;
  text-align: center;
}
<div class="container">
    <img class="image" src="https://homepages.cae.wisc.edu/~ece533/images/airplane.png">
    <div class="to-image-bottom-wrapper">
      <div class="to-image-bottom">I'm div at the bottom of image</div>
    </div>
</div>

为在图像外显示 div 进行了编辑


推荐阅读