为HTML元素添加CSS类的图标图片

12

我需要向 HTML 元素添加图标,类似于 Font Awesome 和 Bootstrap。例如,我需要将图标与 CSS 类相关联。假设类名为 ico,如果我这样做:

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

那么它应该看起来像上面的图片。

我如何使用CSS实现UI设计中非常重要的这个功能?

4个回答

27
你可以使用伪元素来实现这个。

.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>


22

试试这个

.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;
}

1
你可以通过一种非常简单的方式来实现这个功能!只需将图标包装在 <a> 标签中,而不是给 <a> 标签添加图标类即可。
<a href="#"><i class="fas fa-icon"></i>Email Link</a>

我正在使用fas fa-icon类来表示fontawesome库的使用,您必须指定自己的图标。 这里有另一个聪明的提示供您在<a href="">标签中使用: 添加mailto以及您想发送邮件的邮件地址。例如:
<a href="mailto:example@yoursite.com"><i class="fas fa-icon"></i></a>

这将在计算机上打开默认的邮件应用程序,并将收件人填写为“example@yoursite.com”!


0

.question-title{        
        display:block;
        padding-left:30px;
    }
    .question-title:before{
        content: '';
        background:url('https://istack.dev59.com/ZrSlg.webp');
        background-size: 20px 20px;
        position:absolute;
        width:20px;
        height:20px;
        margin-left:-30px;
       
    }
<div class="questions-list">
   <div class="question-item status-open">
      <header class="question-title" >
         Question One                                       
      </header> 
   </div>
   <div class="question-item status-resolved">
      <header class="question-title">
         Question Two                                       
      </header>
   </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接