如何仅在父元素中应用转换?

时间:2016-05-07 09:24:42

标签: html css css3 transform css-transforms

我有HTML

<div id="mydiv" style="color: white; height: 1080px; width: 1920px; transform: translate(-27px, -323px) scale(0.972, 0.401);">
    <div class="player_controls">
        <a class="right carousel-control" href="#" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a> 
    </div>
</div>

此代码包含

transform: translate(-27px, -323px) scale(0.972, 0.401);

适用于子元素player_controls,一个标签。

那么可以做一些不影响子元素的事情吗?

我尝试从player_controls中移除转换

#mydiv .player_controls{transform:''}

1 个答案:

答案 0 :(得分:2)

子元素总是会受到父元素变换的影响。这不是孩子继承的,因此不能通过在孩子身上使用transform: ' 'transform: none来覆盖它。对抗它的一种方法是对孩子应用逆向变换。在这里,由于scale不应该影响孩子,因此应该对父母的比例应用它。

父级的scaleX为0.972,因此childX上的scaleX应为1 / 0.972(反向),即1.028。同样对于scaleY,它应该是1 / 0.401,即2.493。

&#13;
&#13;
#mydiv,#mydiv2 {
  height: 200px;
  width: 200px;
  background: red;
  transform: translate(27px, 23px) scale(0.972, 0.401);
}

#mydiv .player_controls {
  transform: scale(1.028, 2.493);
  transform-origin: left top;
}
&#13;
<h2>With reverse transform on child</h2>
<div id="mydiv">
  <div class="player_controls">
    <a class="right carousel-control" href="#" data-slide="next"><span class="glyphicon glyphicon-chevron-right">Some icon</span>Some text</a> 
  </div>
</div>
<h2>With no reverse transform on child</h2>
<div id="mydiv2">
  <div class="player_controls">
    <a class="right carousel-control" href="#" data-slide="next"><span class="glyphicon glyphicon-chevron-right">Some icon</span>Some text</a> 
  </div>
</div>
&#13;
&#13;
&#13;

如果由于某种原因你无法(或不愿意)对子元素应用反向变换,那么你必须改变你的结构并使子元素成为兄弟元素。

&#13;
&#13;
.container {
  position: relative;
}
#mydiv {
  position: absolute;
  top: 0px;
  left: 0px;
  height: 200px;
  width: 200px;
  background: red;
  transform: translate(27px, 23px) scale(0.972, 0.401);
  transform-origin: 0px 0px;
}
.player_controls {
  position: absolute;
  top: 23px;
  left: 27px;
}
&#13;
<div class="container">
  <div id="mydiv">
  </div>
  <div class="player_controls">
    <a class="right carousel-control" href="#" data-slide="next"><span class="glyphicon glyphicon-chevron-right">Some icon</span>Some text</a> 
  </div>
</div>
&#13;
&#13;
&#13;