如何使父母元素的大小与他的孩子相同,这绝对是他的祖父母

  • 本文关键字:祖父母 孩子 何使 元素 父母 html css
  • 更新时间 :
  • 英文 :


我有一个带有图像元素.child-image的祖父母div .grandparent,它绝对与.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>

我不知道为什么要使这一切变得复杂。我以更简单的形式更改了代码,希望这就是您想要的。如果您想要其他特定的内容,请发表评论。

.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>

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

.grandparent {
  height: 650px;
  max-height: calc(100vh - 100px);
  width: 642px;
  display: inline-block;
  float: left;
  padding: 0;
  margin: 0 0 25px 0;
  background-color: #464646;
  text-align: center;
  position: relative;
}
.parent-wrapper {
  height: 100;
  max-height: calc(100vh - 300px);
  background-color: red;
  position: absolute;
   height: auto;
  width: auto;
  max-height: 100%;
  max-width: 100%;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
   margin: 0 auto;
}
.child-image {
  display: block;
  min-height: 1px;
  cursor: unset;

}

最新更新