Html 如何为背景图像提供alt和标题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11774984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:01:30  来源:igfitidea点击:

How to give alt and title for background image?

htmlcssbackground

提问by Prashobh

How to give alt and title for background image? Is it possible?

如何为背景图像提供alt和标题?是否可以?

<div id="cont"></div>

  #cont
  {
     background:#FFF url(../images/post.png) no-repeat;
  }

回答by Rodik

You cannot give an alt and title for a css background, but you can give a title to the div.

您不能为 css 背景提供 alt 和标题,但可以为 div 提供标题。

<div id="cont" title="Title!"></div>

The title will popup upon mouse-idle over the div element.

当鼠标悬停在 div 元素上时,标题将弹出。

回答by deceze

No, because a background image is only a decorative element which should not have any semantic meaning. HTML is for semanticsand meaning, CSS is just for visual appearances. If the image is so important that it should have a fallback alttext, make it an HTML <img>element.

不,因为背景图像只是一个装饰元素,不应具有任何语义意义。HTML 用于语义含义,CSS 仅用于视觉外观。如果图像非常重要以至于它应该有后备alt文本,请将其设为 HTML<img>元素。

回答by undisclosed

it's simple to give a title tag to the div itself.

为 div 本身提供标题标签很简单。

about the alt, if you desperately need it, the main road to go would be to put an img in the div with height="100%" and width="100%", or, if this gets in your way, add an 1px img in the div, with the alt, but it won't be seen. zindex may also help if the img is getting in your way and oclude other elements.

关于 alt,如果您迫切需要它,主要的方法是在 div 中放置一个高度为“100%”和宽度为“100%”的 img,或者,如果这妨碍了您,请添加一个div中的1px img,带有alt,但不会被看到。如果 img 妨碍您并包含其他元素,zindex 也可能有所帮助。

good luck, alex

祝你好运,亚历克斯

回答by Chris

Yes this is possible within PHP like this..

是的,这在 PHP 中是可能的。

if($moon==0)
  {$icon_moon="background: url(mp0.png); background-repeat: no-repeat; 
   background-size: 15px 15px; background-position: right top";
   $title_mph = "Moon phase new";}

In this case the variable ($icon_moon)is inserted in a table for positioning like this

在这种情况下,变量($icon_moon)被插入到一个表中,以便像这样定位

Adding an Alt text is also possible this way.

也可以通过这种方式添加 Alt 文本。