CSS:拥有一个带有绝对定位图像的 div 填充其父级而不会溢出

问题描述 投票:0回答:1

对于一个新项目,我有一个构造,其中有一个 div(我们称之为父级),其中包含另一个 div(我们称之为子级),其中图像放置在绝对位置,以某种方式相互叠放。

但是,我想实现子级完全填充父级,以最小宽度 100% 和最小高度 100% 居中定位,并且隐藏溢出,因此子级看起来像具有对象拟合的图像盖和物体位置中心。然而,经过一个漫长的夜晚和大量的尝试和错误,我似乎无法正确地实现这一点。 (我可能已经添加了太多的包装器)

父母的

相关代码如下:

<div class="parent" style="height: calc(100vw - 20px); border-radius: 20px; border:1px solid red;">
        <div class="child" style="width: 100%; height: 100%; position: relative; overflow:hidden;"><div class="2d-picture-wrapper" style="position:absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); perspective: calc(19.6vw + 100px);">
           <img src="https://youreka-virtualtours.be/images/objects/389/producten/vlag.png" style="width: 100%" class="2d-picture-base-image">
           <img src="https://youreka-virtualtours.be/images/sessions/389/200/2560px-KPN-Logo.svg.png" style="position: absolute; object-fit: contain; object-position: center; width: 12.6%; height: 10.2%; left: 34.2%; top: 41.3%; transform: rotateX(0.8deg) rotateY(51.5deg) rotateZ(0.7deg) translate(-50%, -50%); transform-style: preserve-3d; transform-origin: center;" class="2d-picture-logo">
        </div>
    </div>
</div>

html css css-position
1个回答
0
投票

首先请注意,您的课程不应以数字开头,因为这是不允许的 如 w3.org 上所述

在 CSS 中,标识符(包括选择器中的元素名称、类和 ID)只能包含字符 [a-zA-Z0-9] 和 ISO 10646 字符 U+00A0 及更高版本,加上连字符 (-) 和下划线(_); 它们不能以数字两个连字符或连字符后跟数字开头。标识符还可以包含转义字符和任何 ISO 10646 字符作为数字代码(请参阅下一项)。例如,标识符“B&W?”可以写成“B&W?”或“B W F”。

然后是你的实际问题: “子”元素已经填充了整个父元素。 但你的基础图像没有。 添加以下属性:

  // fill the entire child with the image
  width: 100%;
  height: 100%;

  // set cover and center the whole image
  object-fit: cover;
  object-position: center;

  // "hide" the corners to fit to your parent border
  border-radius: 20px;

完整示例(注意我已经分离了 html 和 css,还修复了类)

.parent {
  height: calc(100vw - 20px);
  border-radius: 20px;
  border: 1px solid red;
}

.child {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.picture-wrapper {
  position: relative;
  top: 50%;
  left: 50%;
  width: 100%;
  height: 100%;
  transform: translate(-50%, -50%);
  perspective: calc(19.6vw + 100px);
}

.picture-base-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
  border-radius: 20px;
}

.picture-logo {
  position: absolute;
  object-fit: contain;
  object-position: center;
  width: 12.6%;
  height: 10.2%;
  left: 30.2%;
  top: 41.3%;
  transform: rotateX(0.8deg) rotateY(51.5deg) rotateZ(0.7deg) translate(-50%, -50%);
  transform-style: preserve-3d;
  transform-origin: center;
}
<div class="parent">
  <div class="child">
    <div class="picture-wrapper">
      <img src="https://youreka-virtualtours.be/images/objects/389/producten/vlag.png" class="picture-base-image">
      <img src="https://youreka-virtualtours.be/images/sessions/389/200/2560px-KPN-Logo.svg.png" class="picture-logo">
    </div>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.