将图标图像添加到 html 元素的 css 类

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

Adding icon image to css class for html elements

htmlcss

提问by Yazan W Yusuf

I need to add icon image to HTML elements like this in case of font awesome and bootstrap.

在字体真棒和引导程序的情况下,我需要将图标图像添加到这样的 HTML 元素中。

Like this

像这样

enter image description here

在此处输入图片说明

for example I need to associate icon image with css class. Let say class name is ico and if I do something like this

例如,我需要将图标图像与 css 类相关联。假设班级名称是 ico,如果我做这样的事情

 <a href="#" class="ico">Email Link</a>

Then it should appear as in the image above.

然后它应该如上图所示。

How can I accomplish this very important feature for UI design using CSS?

如何使用 CSS 完成 UI 设计的这一非常重要的功能?

回答by Akshay

You can do that using pseudo elements

你可以使用 pseudo elements

.ico{
    width:100px;
    display:block;
    height:20px;
    background:black;
    color:white;
    text-decoration:none;
    padding-left:20px;
}
.ico:before{
    content: '';
    background:url('https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSj3XfIpf-OOJRCcWz4iN2CU3qMKVVbj0p0bRvKNGVo1U9pk_8ZIlyR8pWreA');
    background-size:cover;
        position:absolute;
    width:20px;
    height:20px;
    margin-left:-20px;
}
 <a href="#" class="ico">Email Link</a>
 <a href="#" class="ico">Another Link</a>

回答by Yazan W Yusuf

Try this

尝试这个

.ico:after{
    content: '';
    display: block;
    height: 40px;  /*height of icon */
    width: 40px;  /*width of icon */
    position: absolute;
      /*where to replace the icon */
    top: 0px;
    left: -40px;
      /*background */
    background: #F8E6AE url(ico.gif) no-repeat 0px 0px;
}

回答by Limmelime

You can do this in a very simple way! Just wrap the Icon inside the <a>tag instead of giving the <a>tag the class of the Icon:

你可以用一种非常简单的方式做到这一点!只需将 Icon 包裹在<a>标签内,而不是为<a>标签提供Icon 的类:

<a href="#"><i class="fas fa-icon"></i>Email Link</a>

I'm using the fas fa- class to represent the use of the fontawesome library. Here's another smart tip for you to use in the <a href="">tag: Add mailto and then the mail you want to send a mail to. Example:

我使用 fas fa- 类来表示 fontawesome 库的使用。这是您可以在<a href="">标记中使用的另一个智能提示:添加 mailto,然后添加您要向其发送邮件的邮件。例子:

<a href="mailto:[email protected]"><i class="fas fa-icon"></i></a>

This opens the default mailapplication on the computer with the receiver already fillid in as [email protected]!

这将打开计算机上的默认邮件应用程序,收件人已填写为 [email protected]