【问题标题】:Put icon into a text input field将图标放入文本输入字段
【发布时间】:2026-02-04 18:35:01
【问题描述】:

我尝试将图标放入文本输入字段。
示例:

一种解决方案是使用 background-image,然后使用 padding-left

但我想使用 css sprites。我尝试了下一个代码:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">

    .input {
        padding-left:35px; 
        width: 128px;
        background: Red;

    }



    .sprite:before{
        background: url('http://img45.imageshack.us/img45/4259/buildingssheet7dv.png');
        content: " ";
        position: absolute;
        height:32px;
        width:32px;
        margin: -10px 0 0 -10px;
        z-index:100;
    }


    .sprite:before {
        background-position: -32px 0;
    }

    </style>
</head>
<body>

    <input type="text" class="input sprite"></input>

</body>
</html>

我做错了什么?

【问题讨论】:

    标签: css input icons css-sprites


    【解决方案1】:

    对不起,我不知道为什么您的解决方案不起作用..我自己尝试过,但是 -Tag 里面有 -Tag。

    那么,像这样的东西(又快又脏!)怎么样?

    或者您的意思是:“一种解决方案是使用背景图像,然后使用填充左。”

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    input
    {
        width: 250px;
        height: 65px;
        padding-left: 85px;
    }
    img.home
    {
        width:85px;
        height:65px;
        background: url('http://img45.imageshack.us/img45/4259/buildingssheet7dv.png') 0 0;
        position: absolute;
        left: 10px;
        top: 10px;
    }
    
    </style>
    </head>
    
    <body>
    <input type="text" class="input"/><img class="home">
    </body>
    </html>
    

    【讨论】:

      【解决方案2】:

      我不确定想要的效果是什么,但我想既然你看不到图像,你自己会很难回答这个问题,所以,要指出示例标记中的错误之处,这是在输入元素中使用:before。正如您在this answer 中看到的那样,::before::after 等伪元素只能应用于容器。

      只需将您的标记更改为

      <!DOCTYPE html>
      <html>
      <head>
      <style type="text/css">
      
      .input {
          padding-left: 35px;
          width: 128px;
          background: Red;
      }
      
      .sprite:before {
          background: url('http://img45.imageshack.us/img45/4259/buildingssheet7dv.png');
          content: "";
          position: absolute;
          height: 32px;
          width: 32px;
          margin: -10px 0 0 -10px;
          z-index: 100;
      }
      
      .sprite:before {
          background-position: -32px 0;
      }
      
      </style>
      </head>
      <body>
      
      <div class="sprite">
          <input type="text"class="input"></input>
      </div>
      
      </body>
      </html>
      

      对于您的想法可能是一个很好的起点。

      【讨论】:

        最近更新 更多