【问题标题】:Use position in CSS and calculate height在 CSS 中使用位置并计算高度
【发布时间】:2020-07-25 00:42:37
【问题描述】:

我已将 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>

【问题讨论】:

  • 简短回答:是的,您可以使用 css 执行此操作,但前提是您知道图像的宽/高比。
  • 我怎么知道这个比率?

标签: html css css-position


【解决方案1】:

您可以使用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 而编辑

【讨论】:

  • 在我的例子中,类名为“to-image-bottom”的 div 位于容器的外部。
  • 我不知道你为什么要在这种情况下使用定位,因为你可以将
    放在 标记之后,并且 div 将显示在 img 之后。您可以将标签包装在容器 div 中并为 img 和内部 div 设置“显示:块”和“宽度:100%”
猜你喜欢
  • 2021-07-03
  • 2016-04-21
  • 1970-01-01
  • 2018-01-25
  • 2015-09-24
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
相关资源
最近更新 更多