
使用CSS,我们可以使用‘background-image’属性为HTML元素设置背景图像。此外,在添加背景图像后,还需要设置其尺寸。
我们可以使用CSS的“background-size”属性来设置背景图像的大小。
语法
用户可以按照下面的语法使用CSS来设置背景图像的大小。
background-size: width length | width | contain | inherit | cover | initial
我们可以使用上述值来设置背景图片的大小。在这里,我们已经解释了所有的值。
立即学习“前端免费学习笔记(深入)”;
宽度长度 – 设置背景图像的宽度和高度。用户可以使用像素、百分比或 rem 作为宽度和长度值。
宽度 – 它仅设置图像的宽度并设置“自动”高度。
Contain − 用于设置HTML元素的背景图片,而不会减小背景图片的尺寸。
继承 − 它从父元素的背景图片中继承背景图片大小。
封面 − 它以一种方式设置背景图像的尺寸,使其能够适应HTML元素。
示例 1
在下面的示例中,我们为HTML div元素设置了背景图像。div元素的尺寸为500 X 300。使用background-size属性,我们将背景图像设置为200 X 200的尺寸。
在输出中,用户可以观察到背景图像的大小小于div元素。此外,我们使用了“background-repeat: no-repeat”CSS属性来避免重复。
.div { background-image: url("https://www.tutorialspoint.com/css/images/css-mini-logo.jpg"); background-size: 200px 200px; width: 500px; height: 300px; border: 1px solid blue; background-repeat: no-repeat; } Using the background-size CSS property to set the size of the background image
This is a content of the div.
Example 2
的翻译为:
示例2
在下面的示例中,我们使用“background-size: cover”CSS 属性来设置背景图像的尺寸。
在输出中,我们可以观察到背景图像适合 div 元素。然而,当我们将background-size设置为cover时,一些图像边缘被切掉了。
.div { background-image: url("https://i.pinimg.com/736x/91/aa/88/91aa882cdcb4632063535e86c829d3ba.jpg"); background-size: cover; width: 500px; height: 500px; border: 2px solid green; } Using the background-size CSS property to set the size of the background image
This is a content of the div.
Example 3
的中文翻译为:
示例 3
在下面的示例中,我们使用“background-size: contian”CSS 属性来设置背景图像大小。
在输出中,我们可以看到它设置了背景图像,而没有抑制图像的尺寸。
.div { background-image: url("https://cdn.pixabay.com/photo/2016/06/02/02/33/triangles-1430105__480.png"); background-size: contain; width: 500px; height: 500px; border: 2px solid green; font-size: 3rem; } Using the background-size: contain CSS property to set the size of the background image
Hello! How are you?
Example 4
的翻译为:
示例4
在下面的示例中,我们只给出了’background-size’属性的宽度值。每当我们只使用一个值作为’background-size’属性时,它会将高度设置为自动,用户可以在输出中看到这一点。
.div { background-image: url("https://images.pexels.com/photos/235985/pexels-photo-235985.jpeg?cs=srgb&dl=pexels-pixabay-235985.jpg&fm=jpg"); background-size: 20rem; width: 500px; height: 500px; border: 2px solid green; font-size: 3rem; } Using the background-size: length auto CSS property to set the size of the background image
Hello! How are you?
用户学会了使用 CSS 设置背景图像的大小。我们可以设置自定义尺寸来设置背景图片。此外,我们可以将背景尺寸的宽度和高度设置为“auto”值。如果用户希望使用背景覆盖整个 HTML 元素,则应使用“cover”作为背景大小属性的值。
以上就是使用CSS设置背景图像的大小?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1625648.html
微信扫一扫
支付宝扫一扫