转换容器内的内容

时间:2019-02-21 13:46:55

标签: html css

问题在于,使用属性transform时,父元素会忽略子元素大小的增加。

示例1:使用宽度和高度的子容器

.main {
  display: inline-flex;
  background: green;
  padding: 10px;
}

.element {
  display: block;
  background: red;
  width: 100px;
  height: 100px;
}
<div class="main">
  <div class="element"></div>
</div>

示例2:使用转换的子容器

.main {
  display: inline-flex;
  background: green;
  padding: 10px;
}

.element {
  display: block;
  background: red;
  width: 100px;
  height: 100px;
  transform: scale(1, 2);
}
<div class="main">
  <div class="element"></div>
</div>

如何使transform成为父容器?

1 个答案:

答案 0 :(得分:1)

这是使用js的解决方案。使用jq会使代码更小。

您可以对所有转换后的div运行此功能

 document.querySelectorAll(".element").forEach((x)=>{
    var elPos = x.getBoundingClientRect();
    // make sure that the parent is at least as big as child
    x.parentElement.style.minHeight  = elPos.height +"px";
    x.parentElement.style.minWidth = elPos.width + "px"; 
    // make sure that the top of the child start with the parent
     var elParentPos = x.parentElement.getBoundingClientRect();
     if (elPos.top < elParentPos.top)
      //  Math.abs((elPos.height / elPos.top) is the scale diffrent
     x.style.top = (elParentPos.top * Math.abs((elPos.height / elPos.top))) +"px"
    
 })
.main {
  display: inline-flex;
  background: green;
  padding: 10px;
}

.element {
  display: block;
  background: red;
  width: 100px;
  height: 100px;
  transform: scale(1, 2);
  position:relative;
}
<div class="main">
  <div class="element"></div>
</div>