跳到主要内容

CSS的属性单位

px 像素

  • 设备像素(点), 与设备的分辨率有关
  • 不同分辨率下相同px元素显示会不一样
  • 分辨率越大,像素点就越小,相同px元素就越小

pt 磅

  • 印刷行业常用的单位,是个绝对单位
  • 1pt = 1/72英寸(in)
  • ptpx 之间的换算需要看 DPI(每英寸的像素点, 相同DPI,分辨率越大,显示内容越多)
// 获取屏幕设置的DPI
function getDPI() {
var arrDPI = [];

if (window.screen.deviceXDPI !== undefined) { // IE下支持
arrDPI[0] = window.screen.deviceXDPI; // 相对width
arrDPI[1] = window.screen.deviceYDPI; // 相对height
} else {
// 非IE下兼容
var tmpNode = document.createElement('DIV');
tmpNode.style.cssText = 'width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden';
document.body.appendChild(tmpNode);
arrDPI.push(parseInt(tmpNode.offsetWidth), parseInt(tmpNode.offsetHeight));
tmpNode.parentNode.removeChild(tmpNode);
}

return arrDPI;
}

in 英寸

  • 1英寸 = 2.54厘米 = 25.4毫米 = 72磅(pt)

px 与 mm之间的换算

function width2MM(x) { // width 为 px 单位
const dpi = this.getDPI()[0];
const in = (x / dpi);
return parseInt(in * 25.4);
}
function height2MM(y) {
const dpi = this.getDPI()[1];
const in = (y / dpi);
return parseInt(in * 25.4);
}
function width2PX(x) { // width 为 mm 单位
const dpi = this.getDPI()[0];
const in = (x / 25.4);
return parseInt(in * dpi);
}
function height2PX(y) {
const dpi = this.getDPI()[1];
const in = (y / 25.4);
return parseInt(in * dpi);
}

em

相对于父级元素的 font-size

rem

相对于html根元素的 font-size

vw/vh

相对于浏览器可视区域的长宽

rpx

小程序中的尺寸单位

1rpx = 屏幕宽度/750 px, 所以在屏幕宽度为750的设计稿中,1rpx = 1px