为什么向 img 添加填充会在图像中留下边框,而在使用 CSS 背景 URL 时在 div 上填充不会?



为什么使用img标签强制使用白色边框? 我已经尝试过border:0;,但图片中仍然存在白色边框。 但是,当您使用div时,不会发生这种情况。有没有办法摆脱它?请参阅下面的示例:

div {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
.image {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
<img class="image">
<br>
<div></div>

答案很简单,您错误地使用了img标签,因为:

来源

图片网址。元素是必需的

如果在加载或呈现图像时发生错误,并且已在错误事件上设置了 onerror 事件处理程序,则将调用该事件处理程序。这可能发生在多种情况下,包括:

  • src 属性为空 ("( 或空。

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img

因此,您陷入了浏览器将决定输出与您无法真正控制的错误相关的内容的错误情况。

如果添加alt,您将获得另一个输出:

div {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
.image {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
<img class="image" alt="image">
<br>
<div></div>

我不明白用img这样做的目的是什么,但如果您坚持在里面放置背景图像,请考虑使用有效的图像url。即使是空的 SVG 也可以做到

div {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
.image {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
<img class="image" src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'></svg>" alt="image">
<br>
<div></div>

为什么要为img元素设置背景图像?对于img元素,您可以改用src属性来设置其图像。(我看不出需要设置图像的背景图像。

因此,对于渲染图像,我个人会:

  • 使用img元素并设置(必需!src属性。如果图像是网页(动态(功能/信息内容的一部分,这将是我的偏好。从网站复制/粘贴数据时,将包括它。
  • div元素与 CSS 背景图像一起使用。如果图像是网页(静态(设计的一部分,这将是我的偏好。从网站复制/粘贴数据时,将忽略它。

.background-image {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
box-sizing: border-box; /* do not size by content, but by border */
}
.image {
object-fit: none; /* do not resize image */
object-position: left top; /* do not center image */
width: 100px;
height: 150px;
}
<img class="image" src="https://www.w3schools.com/html/pic_trulli.jpg">
<br>
<div class="background-image"></div>

不使用border: 0;,使用border: none;

您还可以尝试使用box-sizing: border-box;设置元素内部的填充和边距,以便总宽度/高度是确切的总宽度/高度,而不必向公式添加边框、填充和边距。

https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing#:~:text=border%2Dbox%20tells%20the%20browser,to%20absorb%20that%20extra%20width。

border-box 告诉浏览器考虑任何边框和填充 为元素的宽度和高度指定的值。如果您设置 元素的宽度为 100 像素,该 100 像素将包含任何 您添加的边框或填充,内容框将缩小以吸收 那个额外的宽度。

最新更新