html - 与内容无关的图像。背景图像样式属性与 img 标签

标签 html css image background-image

我目前正在为 CMS 创建一个模板,其中可能包含一些与内容无关的图像。它们将显示在文本后面。由于它们将由用户上传,我无法通过 CSS 将它们作为背景图像插入。因此,其他两种可能性也是要么将它们添加为图像并通过 CSS 将它们放置在背景中,要么通过将样式属性添加到父 div 将它们作为背景图像插入。这两个选项都不是很完美,但我想知道这两个选项中哪一个是“更”正确的选项。

最佳答案

HTML spec 开始:

4.7.1.1.9 A purely decorative image that doesn't add any information

Purely decorative images are visual enhancements, decorations or embellishments that provide no function or information beyond aesthetics to users who can view the images.

Mark up purely decorative images so they can be ignored by assistive technology by using an empty alt attribute (alt=""). While it is not unacceptable to include decorative images inline, it is recommended if they are purely decorative to include the image using CSS.

所以任何一种方式都是可以接受的,但使用 CSS 更可取,特别是如果您不想用装饰性图像污染您的标记。

当您需要以不同方式设置单个元素的样式但又不想为它们生成 CSS 规则时,使用内联样式属性是一种可接受的替代方法。最纯粹的方法是在自定义数据属性中指定图像 URL 而不是内联样式属性,但您无法获取该属性的值并将其应用于 background-image 属性从 no browser supports that ability yet 开始使用 CSS,因此内联样式是您的下一个最佳选择。

关于html - 与内容无关的图像。背景图像样式属性与 img 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36421648/

相关文章:

javascript - 使用Jquery根据条件动态添加cssClass

html - Bootstrap 4 在不同行的图像下方对齐 block 中的文本

html - 通过 CSS 从底部裁剪图像

Android:如何接收完整的 html,图像和 css 文件作为字符串?

html - 为什么我的表没有行?

jquery - 使用有效样式使用 jQuery 查找 HTML 元素(从 CSS 类继承的样式,而不是在元素上显式)

html - 我的模板响应式菜单 Bootstrap 不起作用?

html - Bootstrap 轮播的分辨率和宽高比图像大小

CSS 相对(相对于什么?)位置

html - 我可以在 img 标签中明确指定 MIME 类型吗