CSS使背景图像使用字体字符 [英] CSS make background-image use font character

查看:81
本文介绍了CSS使背景图像使用字体字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用字体字符(例如,来自font-awesome)作为输入元素的背景图像.

I'd like to use a font character (e.g. from font-awesome) as a background-image of an input element.

<style>
#id {
    background-image: content('\f2d3'); /* content instead of url() */
    background-position: right center;
}
</style>

<input id="test" />

我的猜测是,我要么将角色另存为图像,要么将伪元素:after content 一起使用,并放置适当的位置来实现此目的.只是想看看是否有更好的解决方案.好像可以在SVG中访问角色并将内联SVG用作内容吗?

My guess is that I'll either save the character as an image or use the pseudo-element :after with content and adequate positioning to achieve this. Just wanted to see if there are better solutions. Like would it be possible to access the character in SVG and use inline SVG as content?

我使用SVG提出了部分解决方案(请参见 https://fiddle.jshell.net/92h52e65/4/),但是仍然存在使用正确字体的问题.

I made a part solution with SVG (see https://fiddle.jshell.net/92h52e65/4/) but that still has the problem of using the correct font.

<style>
#input1 {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="30px" height="20px"><text x="5" y="15" font-family="FontAwesome">x&#xf2d3;</text></svg>');
  background-position: right center;
  background-repeat: no-repeat no-repeat;
}
</style>

<input id="input1" placeholder="insert some text here" size="30" required />

要使其在IE和FF中正常工作,我必须使用base64编码而不是utf8.我将utf8留在此处以使其更具可读性.

For this to work in IE and FF I had to use base64-encoding instead of utf8. I left the utf8 here to make it more readable.

推荐答案

是否有特定的原因需要使用 background-image ?

Is there a particular reason you need to use background-image?

如果没有,您可以这样:

If not, you can do it this way:

.input1wrap::after {
  font-family: FontAwesome;
  content: '\f2d3';
  margin-left: -1.5em;
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<span class="input1wrap">
  <input id="input1" placeholder="insert some text here" size="30" required />
</span>

这篇关于CSS使背景图像使用字体字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆