没有 scale
代码工作正常,但我需要将一个已经缩放 的元素垂直居中。我正在寻找使用 CSS 或 JS 方法的解决方案。
我也不能使用 transform-origin
CSS 属性,因为它在我需要支持的某些浏览器中不受支持...
https://jsfiddle.net/o62ja9r6/17/
.container {
position: fixed;
border: 2px dashed blue;
width: 400px;
height: 300px;
}
.slide {
position: absolute;
width: 76px;
height: 169px;
background-color: red;
}
.vertical-center {
top: 50%;
transform: scale(0.4) translateY(-50%);
/* transform: translateY(-50%); // <--- it works */
}
<div class="container">
<div class="slide vertical-center">
</div>
</div>
最佳答案
顺序很重要,将 translateY
替换为 scale
。
.container {
position: fixed;
border: 2px dashed blue;
width: 400px;
height: 300px;
}
.slide {
position: absolute;
width: 76px;
height: 169px;
background-color: red;
}
.vertical-center {
position: relative;
top: 50%;
transform: translateY(-50%) scale(0.4);
}
<div class="container">
<div class="slide vertical-center">
</div>
</div>
快速解释
如果您有一个 100px
高的元素,并且您将它沿 y 轴平移 -50%
,它将向上移动其高度的 50%,这将是 50px
。如果您首先缩放100px
高元素,将其缩小到其高度的40%
,那么它将是40px
当您尝试沿 y 轴平移它时会变高,这只会将它向上移动 20px
。
关于javascript - 如何垂直居中绝对定位的缩放元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43099462/