我的 html 中有一个图像标签:
<img class="fruit1" />
以及我的CSS中的以下内容:
.fruit1 {
background-image: url('./images/apple.png');
}
但我无法显示实际图像,这是在 css 中分配图像并将其显示在视图中的正确方法吗?
In practice you should use a src attribute if the image is part of the page's content:
<img class="fruit1" src="images/apple.png" />
Background images are traditionally used to enhance content by replacing appropriate text (often headers):
<h2 class="apples">Our Apples</h2>
.apples {
background-image: url('./images/apple.png');
width: 100px;
height: 100px;
text-indent: -99999px; /* hide the text with a negative text-indent */
}
<style>
.fruit1 {
background-image: url('./images/apple.png');
height:100px;
width:100px;
background-repeat:no-repeat;
}
</style>
<img class="fruit1" />
如果您有图像作为背景图像,也可以使用图像的宽度和高度。在这种情况下,您不应该有图像标签
<div class="fruit1" ></div>
.fruit1 {
background-image: url('./images/apple.png');
width: 200px;
height: 200px
}
像你所做的那样使用 HTML 来显示它;
<img class="fruit1" src= "./images/apple.png" width="200px" height="200px" />