假设我有以下html:
html,body{ height: 100%; overflow-y: hidden; } div{ background: url(path) no-repeat center; width: 100%; height: 100%; background-size: contain; }
在这里,背景大小包含并且是全宽和高度为100%,但背景图像的区域未被div完全覆盖.
那么,有没有办法得到被覆盖图像的宽度和高度?
解决方法
documentation提到以下内容:
This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.
这将适用于以下代码:
imageRatio = imageWidth / imageHeight; if (imageRatio >= 1) { // landscape imageWidth = areaWidth; imageHeight = imageWidth / imageRatio; if (imageHeight > areaHeight) { imageHeight = areaHeight; imageWidth = areaHeight * imageRatio; } } else { // portrait imageHeight = areaHeight; imageWidth = imageHeight * imageRatio; if (imageWidth > areaWidth) { imageWidth = areaWidth; imageHeight = areaWidth / imageRatio; } }
根据图像方向(纵向或横向),它首先增长最长边缘,然后在仍然保留纵横比的同时缩小必要的最短边.