织梦CMS - 轻松建站从此开始!

abg欧博官网|登陆|游戏|

Transform: translate(

时间:2025-09-04 04:34来源: 作者:admin 点击: 3 次
The reason why transform: translate(-50%, -50%) is required is because you want the center of the element to line up with the center of its parent. In

The reason why transform: translate(-50%, -50%) is required is because you want the center of the element to line up with the center of its parent. In simple terms, it can be boiled down to translateX(-50%) translateY(-50%), which means:

move me leftwards by 50% of my width, along the x-axis, and

move me upwards by 50% of my height, along the y-axis

This effectively moves the center of the element to its original top left corner. Remember then when you set left: 50%; top 50% on the element, you are moving its top left corner to the center of its parent (which means it is not visually centered at all). By moving the element back leftwards and upwards by half of its width and height respectively, you are sure that its center now aligns with the parent's center, making it visually horizontally + vertically centered.

As a proof of concept, see the code snippet below: hover over the parent to cause the child element's "ghost" to reposition itself by means of transform: translate(-50%, -50%):

body { margin: 0; padding: p; } .parent { background-color: #ccc; width: 100vw; height: 100vh; position: relative; } .child { background-color: rgba(0,0,255,0.5); width: 50px; height: 50px; position: absolute; top: 50%; left: 50%; } .child::before { background-color: rgba(255, 0, 0, 0.5); position: absolute; top: 0; left: 0; width: 50px; height: 50px; content: ''; transition: all .5s ease-in-out; } body:hover .child::before { transform: translate(-50%, -50%); } <div> <div></div> </div>

(责任编辑:)
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:
发布者资料
查看详细资料 发送留言 加为好友 用户等级: 注册时间:2025-09-07 06:09 最后登录:2025-09-07 06:09
栏目列表
推荐内容