具有 CSS 属性的解决方案
我们可以使用 <img> 标签设置图像并将 object-fit 属性设置为“cover”。
在 <img> 标签上使用 object-fit 属性的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> body { margin: 0; } img { display: block; width: 100vw; height: 100vh; object-fit: cover; } </style> </head> <body> <img src="onitroad.com" /> </body> </html>
在上面的例子中,我们还指定了图像的宽度和高度,并将显示属性设置为“块”。
其中内容被调整大小以保持其纵横比,同时填充元素的整个内容框。
让我们看另一个例子,我们将 <img> 替换为背景图像。
用背景图像替换 <img> 的示例:
<!DOCTYPE html> <html> <head> <title>文档的标题</title> <style> body { margin: 0; } img { position: fixed; width: 0; height: 0; padding: 40vh 40vw; background: url(https://onitroad.com/test.png) no-repeat; background-size: cover; } </style> </head> <body> <img src="https://onitroad.com/bg.png" alt="Background-size example" /> </body> </html>
其中我们使用 background 属性设置背景图像,然后使用“cover”值指定 background-size 属性。
此外,我们将位置设置为“固定”并添加了宽度、高度和填充属性。
可以在 HTML <img> 标签上使用等效于 CSS background-size 属性的“cover”值。
其中我们将展示两种方法。
日期:2020-06-02 22:15:12 来源:oir作者:oir