使用“数据:”的 CSS 透明背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5588043/
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-30 00:09:48  来源:igfitidea点击:

CSS transparent background image using "data:"

imagebase64background-imagecss

提问by Alex

I've seen on some sites that you can include images in CSS using a "data" keyword:

我在一些网站上看到,您可以使用“数据”关键字在 CSS 中包含图像:

.stuff {
  background: transparent url(data:image/gif;base64,SOMEWEIRDCODEHERE) repeat center top;
}

the weird code looks like a base64 ecoded string like:

奇怪的代码看起来像一个 base64 编码的字符串,如:

R0lGODlhMwAxAIAAAAAAAP/// yH5BAAAAAAALAAAAAAzADEAAAK8jI+pBr0PowytzotTtbm/DTqQ6C3hGX ElcraA9jIr66ozVpM3nseUvYP1UEHF0FUUHkNJxhLZfEJNvol06tzwrgd LbXsFZYmSMPnHLB+zNJFbq15+SOf50+6rG7lKOjwV1ibGdhHYRVYVJ9Wn k2HWtLdIWMSH9lfyODZoZTb4xdnpxQSEF9oyOWIqp6gaI9pI1Qo7BijbF ZkoaAtEeiiLeKn72xM7vMZofJy8zJys2UxsCT3kO229LH1tXAAAOw==

R0lGODlhMwAxAIAAAAAAAP /// yH5BAAAAAAALAAAAAAzADEAAAK8jI + pBr0PowytzotTtbm / DTqQ6C3hGX ElcraA9jIr66ozVpM3nseUvYP1UEHF0FUUHkNJxhLZfEJNvol06tzwrgd LbXsFZYmSMPnHLB + zNJFbq15 + SOf50 + 6rG7lKOjwV1ibGdhHYRVYVJ9Wn k2HWtLdIWMSH9lfyODZoZTb4xdnpxQSEF9oyOWIqp6gaI9pI1Qo7BijbF ZkoaAtEeiiLeKn72xM7vMZofJy8zJys2UxsCT3kO229LH1tXAAAOw ==

look pretty cool :D

看起来很酷:D

I was wondering how can I include a transparent 1x1 pixel GIF like this? Does anyone know the data code for such a image?

我想知道如何包含这样的透明 1x1 像素 GIF?有谁知道这种图像的数据代码?

Is it a good idea to do this for small and very common images? Do all browsers support this?

对小而非常常见的图像执行此操作是否是个好主意?所有浏览器都支持吗?

回答by Shaz

That's called the The data URI scheme

这就是所谓的数据 URI 方案

Use the Data URI Kitchento convert just about anything to data uri's. Link: http://software.hixie.ch/utilities/cgi/data/data

使用Data URI Kitchen将几乎所有内容转换为数据 uri。链接:http: //software.hixie.ch/utilities/cgi/data/data

回答by Mark Kahn

data:image/gif;base64,R0lGODlhAQABAPAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==

Nothing wrong with doing this, you save an HTTP round-trip. The only downside is that it doesn't work in older versions of IE (IE8, I believe, started to support it)

这样做没有错,您节省了 HTTP 往返。唯一的缺点是它在旧版本的 IE 中不起作用(我相信 IE8 开始支持它)

回答by rushkeldon

this is a transparent GIF of one pixel

这是一个像素的透明 GIF

background-image: url( data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== );

回答by Bill Criswell

Depending on the browsers you need to support you might be better off using rgba(). I know this question is a little old.

根据您需要支持的浏览器,您最好使用rgba(). 我知道这个问题有点老了。

body {
  background-color: rgba( 0, 0, 0, .5 ); 
}

回答by callum

Up-to-date browser support details for data URIs:

数据 URI 的最新浏览器支持详细信息:

http://caniuse.com/#feat=datauri

http://caniuse.com/#feat=datauri