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

55 阅读1分钟

我们都知道元素可以通过百分比来定位,比如背景图片可以通过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. 在这里插入图片描述

对元素的位置控制知识另可以参考:点我


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