CSS图片的百分比位置是如何进行计算的 ——w3c权威解释

我们都知道元素可以通过百分比来定位,比如背景图片可以通过background-position进行定位,图片裁剪可以通过object-position进行定位,常用的有数值(1px,2px)、关键字(left,top)、百分数(50%,50%),那么问题来了,如果设置为百分数是如何计算的?

如果用数值,背景图片将会相对于该元素进行计算,如

background-position:20px 20px;

背景图片的左上角将会出现在元素左上角下方20px,左边20px的地方

background-position:20% 20%;

此时背景图片将会将自身(20%,20%)的地方,对应到元素(20%,20%)的地方
在这里插入图片描述
可以看出两张背景图位置有明显的差异,事实上第二张背景图左上角到元素左上角的距离为14px(元素尺寸为150*150,背景图尺寸为80*80),计算公式很简单

150*0.2 - 80*0.2 = 14

对此W3C官方解释

A percentage X aligns the point X% across (for horizontal) or down (for vertical) the image with the point X% across (for horizontal) or down (for vertical) the element’s padding box. For example, with a value pair of ‘0% 0%’,the upper left corner of the image is aligned with the upper left corner of the padding box. A value pair of ‘100% 100%’ places the lower right corner of the image in the lower right corner of the padding box. With a value pair of ‘14% 84%’, the point 14% across and 84% down the image is to be placed at the point 14% across and 84% down the padding box.
在这里插入图片描述

对元素的位置控制知识另可以参考:talk about background position values


😁欢迎加入QQ群交流: [游戏-Web-开发技术栈 ☄️] ‘300567032’
点击下方图标一键加入!
游戏-Web-开发技术栈 ☄


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值