HTML / CSS Como adicionar um ícone de imagem ao tipo de entrada = “botão”?


110

Estou usando o CSS abaixo, mas ele coloca uma imagem no centro do botão. Há alguma maneira de alinhar um ícone à esquerda ou à direita usando <input type="button">, de modo que o texto e a imagem se ajustem e se alinhem bem?

background: url('/common/assets/images/icons/16x16/add.png');
background-position:center;
background-repeat:no-repeat;

Respostas:


143

Se você realmente precisa usar input, tente isto:

background-image: url(...);
background-repeat: no-repeat;
background-position: <left|right>;
padding-<left|right>: <width of image>px;

Normalmente é um pouco mais fácil de usar buttoncom um imginterior:

<button type="submit"><img> Text</button>

No entanto, as implementações do navegador buttonpara envio são inconsistentes, assim como o fato de que todos os valores do botão são enviados quando buttoné usado - o que elimina a detecção de "qual botão clicado" em um formulário de envio múltiplo.


não precisa, mas eu aqui a tag de botão está cheia de erros no ie 6 ou se comporta de maneira diferente em alguns navegadores?
— Brett

Tanto quanto eu experimentei, button(com tipo submit) funciona de forma idêntica, inputcom exceção de permitir elementos dentro (em vez de apenas estilos aplicados a ele).
— Delan Azabani

8
A parte 'problemática' da <button>implementação do IE vem do fato de que 1) em um POST / GET, ele envia os 'valores' para cada botão, e não apenas aquele clicado, e 2) Em vez de enviar o valueatributo real , o IE gosta para enviar o conteúdo (HTML interno) do botão. Esses fatos tornam a <button>tag não confiável se a ação executada depender do botão em que o usuário clicou.
— Duroth

Muito bem, Duroth. Sim, isso certamente é um kicker para coisas como um formulário de edição de postagem que tem "Visualizar" e "Enviar", etc.
— Delan Azabani

3
Você pode usar <button>e de forma <input type=button>intercambiável. Se você não quiser enviar <button> no IE, defina seu tipo da seguinte forma:<button type="button">Text</button>
— Darcy

74

Isso deve fazer o que você deseja, supondo que a imagem do botão seja de 16 por 16 pixels.

<input type="button" value="Add a new row" class="button-add" />
input.button-add {
    background-image: url(/images/buttons/add.png); /* 16px x 16px */
    background-color: transparent; /* make the button transparent */
    background-repeat: no-repeat;  /* make the background image appear only once */
    background-position: 0px 0px;  /* equivalent to 'top left' */
    border: none;           /* assuming we don't want any borders */
    cursor: pointer;        /* make the cursor like hovering over an <a> element */
    height: 16px;           /* make this the size of your image */
    padding-left: 16px;     /* make text start to the right of the image */
    vertical-align: middle; /* align the text vertically centered */
}

Botão de exemplo:

botão de exemplo

Atualizar

Se você usar Less, este mixin pode ser útil.

.icon-button(@icon-url, @icon-size: 16px, @icon-inset: 10px, @border-color: #000, @background-color: transparent) {
    height: @icon-size * 2;
    padding-left: @icon-size + @icon-inset * 2;
    padding-right: @icon-inset;
    border: 1px solid @border-color;
    background: @background-color url(@icon-url) no-repeat @icon-inset center;
    cursor: pointer;
}

input.button-add {
    .icon-button("http://placehold.it/16x16", @background-color: #ff9900);
}

O acima é compilado em

input.button-add {
  height: 32px;
  padding-left: 36px;
  padding-right: 10px;
  border: 1px solid #000000;
  background: #ff9900 url("http://placehold.it/16x16") no-repeat 10px center;
  cursor: pointer;
}

JSFiddle


você não precisa de aspas no argumento do método url ()?
— ecbrodie


10
<button type="submit" style="background-color:transparent; border-color:transparent;"> 
  <img src="images/button/masuk.png" height="35"/>
</button>
<button type="reset" style="background-color:transparent; border-color:transparent;"> 
  <img src="images/button/reset.png" height="35"/>
</button>

Espero que isso ajude você.


2

Se você estiver usando spritesheets, isso se torna impossível e o elemento deve ser agrupado.

.btn{
    display: inline-block;
    background: blue;
    position: relative;
    border-radius: 5px;
}
.input, .btn:after{
    color: #fff;
}
.btn:after{
    position: absolute;
    content: '@';
    right: 0;
    width: 1.3em;
    height: 1em;
}
.input{
    background: transparent;
    color: #fff;
    border: 0;
    padding-right: 20px;
    cursor: pointer;
    position: relative;
    padding: 5px 20px 5px 5px;
    z-index: 1;
}

Confira este violino: http://jsfiddle.net/AJNnZ/


1

você pode tentar este truque!

1ª) faça isso:

<label for="img">
   <input type="submit" name="submit" id="img" value="img-btn">
   <img src="yourimage.jpg" id="img">
</label>

2ª) estilize!

<style type="text/css">
   img:hover {
       cursor: pointer;
   }
   input[type=submit] {
       display: none;
   }
</style>

Não está limpo, mas fará o trabalho!


1

Basta adicionar o ícone no elemento do botão aqui está o exemplo

   <button class="social-signup facebook"> 
     <i class="fa fa-facebook-official"></i>  
      Sign up with Facebook</button>


0

O que eu faria é o seguinte:

Use um tipo de botão

 <button type="submit" style="background-color:rgba(255,255,255,0.0); border:none;" id="resultButton" onclick="showResults();"><img src="images/search.png" /></button>

Usei a cor de fundo: rgba (255,255,255,0,0); Para que a cor de fundo original de um botão desapareça. O mesmo com a borda: nenhum; isso removerá a borda original.


0

Este é o estilo mínimo necessário, ajustando a imagem ao tamanho do botão padrão:

<input type="button" value=" " style="background-image: url(http://www.geppoz.eu/geppoz.png);background-size:100% 100%;">

o valor "espaçado" é necessário para manter o alinhamento da linha de base, apenas no caso de você precisar ...


0

A resposta de sshow também me ajudou:

Navigation.css :

[...]

.buttonConfiguration {
    width: 40px;
    background-color: red; /* transparent; */
    border: none;
    color: white;
    padding: 5px 10px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-family: corbel;
    font-size: 12px;
    font-weight: normal;
    margin: 1px 1px;
    cursor: pointer;

    background-image: url('../images/icons5/gear_16.png');
    background-position: center; /* 0px 0px; */
    background-repeat: no-repeat;
    vertical-align: middle;
}

[...]

frameMenu.php :

[... PHP, Javascript and HTML code ...]

<!-- <li><a target="frameBody" href="admin/conf/confFunctions.php"><input type="button" class="buttonSuperAdmin" value="<?= $oLanguage->getExpression('confSettings', 'title', 'C e n t e r s') ?>"></a> -->
<li><a target="frameBody" href="admin/conf/confFunctions.php"><input type="button" class="buttonConfiguration" value=""></a>
<ul>
<li><a target="frameBody" href="admin/conf/getglobals.php "><input type="button" class="buttonSuperAdminSub" value="<?= $oLanguage->getExpression('centerSettings', 'confAdmin1', 'GetGlobals') ?>"></a></li>
<li><a target="frameBody" href="admin/conf/getcwd.php "><input type="button" class="buttonSuperAdminSub" value="<?= $oLanguage->getExpression('confSettings', 'centerAdmin2', 'GetCWD') ?>"></a></li>
</ul>
</li>

[...]

Eu testei isso com sucesso nas últimas versões do Firefox e Chrome (em 9 de fevereiro de 2019).


0

O que isso parece

Isso funciona bem para mim, e estou lidando com o foco e clique em CSS também (alterando a cor de fundo):

HTML (aqui mostrando 2 imagens, imagem1 em cima da imagem2):

<button class="iconButton" style="background-image: url('image1.png'), url('image2.png')"
  onclick="alert('clicked');"></button>

CSS (minhas imagens têm 32px X 32px, então dei a elas 4px para preenchimento e um arredondamento de borda de 5px):

.iconButton {
    width: 36px;
    height: 36px;
    background-color: #000000;
    background-position: center;
    background-repeat: no-repeat;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    outline: none;
}

.iconButton:hover {
    background-color: #303030;
}

.iconButton:active {
    background-color: #606060;
}

button::-moz-focus-inner {
    border: 0;
}

-2
<img src="http://www.pic4ever.com/images/2mpe5id.gif">
            <button class="btn btn-<?php echo $settings["button_background"]; ?>" type="submit"><?php echo $settings["submit_button_text"]; ?></button>

por favor acrescente uma explicação à sua resposta.
— warunapww

Precisa de um ">" para fechar a tag img.
— harrypujols de

1
Por que você está usando PHP?
— Top Cat de
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.