如何使父元素的大小与他的孩子的大小完全相同,而他的孩子绝对位于祖父母的位置?

时间:2019-05-02 13:20:49

标签: html css

我有一个祖父母div .grandparent,其图像元素.child-image相对于.grandparent处于绝对位置。我希望包装元素.parent-wrapper(用于包装图像)的宽度和高度与其子元素.child-image相同。可能吗?我尝试了几乎所有内容,但仍然无法解决。

这是codepen:https://codepen.io/anon/pen/MRNwoJ?editors=1100

.grandparent {
  height: 650px;
  max-height: calc(100vh - 100px);
  width: 642px;
  position: relative;
  display: inline-block;
  float: left;
  padding: 0;
  margin: 0 0 25px 0;
  background-color: #464646;
  text-align: center;
}

.parent-wrapper {
  height: unset;
  max-height: calc(100vh - 300px);
  background-color: red;
  float: left;
}

.child-image {
  display: block;
  margin: 0 auto;
  min-height: 1px;
  height: auto;
  width: auto;
  max-height: 100%;
  max-width: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  cursor: unset;
}
<div class="grandparent">
  <div class="parent-wrapper">
    <img class="child-image" src="https://cfl.dropboxstatic.com/static/images/index/rebrand/co_create/desktop/dropbox_digital_desktop_02-vflq-5NiU.jpg">
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

从子图像中删除绝对位置并将其分配给父div,这样父div的位置和大小将与子div相同。

constexpr

}

答案 1 :(得分:0)

我不知道你为什么要把这些复杂化。我已经以更简单的形式更改了代码,希望这就是您想要的。如果您想要其他特定的东西,请发表评论。

.grandparent {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 650px;
    width: 100%;
    margin: 0 0 25px 0;
    background-color: #464646;
    text-align: center;
  }

  .parent-wrapper {
    display: inline-block;
  }
  
  img {
   max-width: 100%;
  }
<div class="grandparent">
  <div class="parent-wrapper">
    <img class="child-image" src="https://cfl.dropboxstatic.com/static/images/index/rebrand/co_create/desktop/dropbox_digital_desktop_02-vflq-5NiU.jpg">
  </div>
</div>

相关问题