如何在绝对位置父级上设置子级高度

How to set the children height on absolute position parent

我对如何使子项大小跟随其父项有疑问。以下案例

HTML

<div class="video">

  <div class="spot">
    <img src="..." alt="">
    <button>x</button>
  </div>

</div>

CSS

.video {
  width: 600px;
  height: 500px;
  background: #000;
  position: relative;
}

.spot {
  position: absolute;
  max-height: 30px;
  top: 0;
  left: 0;
  display: table;
  margin: 0;
  max-width: 100%;
  /* width: 16%;  only height can affect image on content*/
}

.spot img {
  width: 100%;
  height: 100%;
}

.spot button {
  position: absolute;
  top: 0;
  left: 100%;
  margin-left: -24px;
}

我要做的是让图像跟随光斑高度。因为如果我设置宽度(无论大小),图像将遵循点宽度。有人知道怎么做吗?

我也创建了 jsfiddle https://jsfiddle.net/isatrio/yosfep6r/14/

您已设置 max-width 而不是 widthmax-width 不会将 width 设置为给定值,它只会阻止 width 超过给定值。

.spot {
  position: absolute;
  height: 30px;
  top: 0;
  left: 0;
  display: table;
  margin: 0;
  width: 100%;
}

您的图片已经符合您的 .spot 高度。检查 spot 上的边框。或者你的意思是溢出?或者您想让您的 .spot 跟随您的 .video

console.log(".spot height: " + $(".spot").innerHeight());
console.log("img height: " + $(".spot img").height());
.video {
  width: 600px;
  height: 500px;
  background: #000;
  position: relative;
}

.spot {
  border: red 2px solid;
  position: absolute;
  height: 40%;
  /*width: 20%;*/
  top: 0;
  left: 0;
  margin: 0;
  padding: 0;
  max-width: 100%;
  overflow: hidden;
}

.spot img {
  /*width: 150%;*/
  height: 100%;  
}

.spot button {
  position: absolute;
  top: 0;
  left: 100%;
  margin-left: -24px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="video">

  <div class="spot">
    <img src="https://creativeblossoming.files.wordpress.com/2013/10/navy-living-room.jpg" alt="">
    <button>x</button>
  </div>

</div>