transform:translate(-50%,-50%) 与transform:scale() 不能很好地配合

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

我使用position:absolute;将我的元素与“play__circle”类居中; (父容器设置为position:relative;)但是当我使用transform:scale()时,元素不再停留在中心。 最初“play__circle”是隐藏的,但悬停时其不透明度设置为 1 且比例设置为 (0.7)。

.container{
  width: 200px;
  height: 250px;
  background-color: rgba(208, 174, 191, 0.8);
  position: relative;
  padding:5px;
}

.play__circle{
  width: 60px;
  height: 60px;
  background-color: gray;
  border-radius: 100%;
  position: absolute;
  top:50%;
  left:50%;
  opacity:0;
  transform:translate(-50%, -50%);
  transition: opacity 300ms ease-in-out, transform    300ms ease-in-out;
}

.container:hover .play__circle{
  opacity: 1;
  transform:scale(0.7)
}

.content__one{
  width: 100%;
  height: 50%;
  background-color: rgba(205, 184, 86, 0.8);
}

.content__two{
  width: 100%;
  height: 50%;
  background-color: rgba(232, 125, 52, 0.8);
}
<div class="container">
  <div class="play__circle">

  </div>
  <div class="content__one">

  </div>
  <div class="content__two">

  </div>
</div>

html css
1个回答
0
投票

TL;博士。
transform
动画时需要完整指定属性

您的情况主要关注的是您的基本样式中有

transform: translate(-50%, -50%);
,并且在悬停时通过
transform: scale(0.7);
对其进行动画处理。当使用多个值对 CSS 属性进行动画处理时,您通常需要包含所有自定义设置值。

也就是说,当您悬停鼠标时,CSS 将在 scale(1)

scale(0.7)
值之间进行
only
转换,并忽略
translate(-50%, -50%)
,因为它未指定。

此外,您还需要将

transform-origin
指定到左上角,因为您通过
transform
重新定位了它,并且它不再从视觉中心产生动画。请参阅下面的片段。

.container{
  width: 200px;
  height: 250px;
  background-color: rgba(208, 174, 191, 0.8);
  position: relative;
  padding:5px;
}

.play__circle{
  width: 60px;
  height: 60px;
  background-color: gray;
  border-radius: 100%;
  position: absolute;
  top:50%;
  left:50%;
  opacity:0;
  transform:translate(-50%, -50%);
  transform-origin: top left; /* This line is added */
  transition: opacity 300ms ease-in-out, transform    300ms ease-in-out;
}

.container:hover .play__circle{
  opacity: 1;
  transform:scale(0.7) translate(-50%, -50%); /* This line is edited */
}

.content__one{
  width: 100%;
  height: 50%;
  background-color: rgba(205, 184, 86, 0.8);
}

.content__two{
  width: 100%;
  height: 50%;
  background-color: rgba(232, 125, 52, 0.8);
}
<div class="container">
  <div class="play__circle">

  </div>
  <div class="content__one">

  </div>
  <div class="content__two">

  </div>
</div>

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