html - 如何使父元素与绝对定位到祖 parent 的子元素大小相同?

标签 html css

我有一个祖 parent div .grandparent,里面有一个图像元素 .child-image,它相对于 .grandparent 绝对定位。我希望包装器元素 .parent-wrapper(包装图像)与其子元素 .child-image 具有相同的宽度和高度。是否可以?我几乎尝试了所有方法,但仍然无法弄清楚。

这是代码笔: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>

关于html - 如何使父元素与绝对定位到祖 parent 的子元素大小相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55953434/

相关文章:

css - 如何防止标签自动换行?

html - 外部 CSS 不能只在一页上工作

html - 当我的屏幕宽度小于 700 像素时,如何在页脚中将社交图标分成两行?

html - Margin 和 Padding 使图像变大

javascript - 在 div 中选择图像

jquery - 有哪些选项可以让文本/列表项出现在列中?

javascript - 如何使用<a>标签下载大尺寸图像

javascript - 如何阻止用户输入某些字符?

javascript - jQuery 搜索表单 - 如何定向到内部页面

html - 等于基于另一个属性的 CSS 属性的值