看来,当缩小以前不适合其容器的元素时,margin: 0 auto
将不再使元素在其父元素中居中(请注意,使用transform-origin: center center
并没有解决这个问题)。这是因为自动边距似乎在缩放之前而不是之后应用(我期望后者)。
在玩这个时,我最终设法将元素在其容器内居中,但仅使用绝对定位:
position: absolute;
transform: translateX(-50%) scale(0.5, 0.5);
left: 50%;
这是一种非常流行的技术,但在这种特殊情况下,放置 translateX 函数非常重要before缩放函数,因为它们按定义的顺序执行。
以下是说明该问题的代码片段(也在 CodePen 上:https://codepen.io/liranh85/pen/qVewQp https://codepen.io/liranh85/pen/qVewQp)
.container {
border: 3px solid black;
width: 500px;
height: 200px;
margin: 0 auto;
position: relative;
}
.scaled {
background-color: blue;
width: 600px;
/* width: 400px; */
height: 100%;
transform: scale(0.5, 0.5);
/* transform: translateX(-50%) scale(0.5, 0.5); */
margin: 0 auto;
/* position: absolute;
left: 50%; */
}
<div class="container">
<div class="scaled"></div>
</div>
请注意:
- 当元素的宽度大于其容器的宽度时,该元素不会使用自动边距居中。
- 当给缩放元素的宽度小于其容器时,缩放后它将保持居中(例如尝试使用
width: 400px
).
- 当使用绝对定位时,如上所述,可以将元素居中。
我在想:
- 还有其他人遇到过这个问题吗?
- 这是将此类元素居中的最佳方式吗?
- 我说自动边距不能用于居中这样的元素是否正确?
你需要使用
transform-origin: center;
看一下这方面的一些文档https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)