Explain Codes LogoExplain Codes Logo

Html / CSS How to add image icon to input type="button"?

html
responsive-design
css
accessibility
Alex KataevbyAlex Kataev·Feb 23, 2025
TLDR

Quickly add an icon to a <input type="button"> using CSS's background properties:

<input type="button" class="icon-btn">
.icon-btn { /* Path to File of Painted Squidward */ background: url('icon.png') no-repeat center / contain; border: none; /* Chase away the border goblins! */ padding: 10px; /* Cozy padding for Squidward */ height: 20px; /* Match Squidward's height */ width: 20px; /* And his width */ cursor: pointer; /* Because it's more than just a pretty face, it's clickable! */ }

Let's tailor the height and width to fit our icon's dimensions.

Refine and compatibility: Make the button shine in all browsers

Add extra gears to the button for usability & visual balance.

Padding Adjustment: Give the icon some room

Add space around the icon so it doesn't eat the text:

.icon-btn { /* Space for icon (and his hat) */ padding-left: 30px; }

This space gives room for the icon's size and the button's overall size.

Sprites: When dealing with an army of icons

Use CSS sprites to fight off HTTP request villains when dealing with multiple icons:

.icon-btn { /* Group photo of our icon squad */ background-image: url('icons-sprite.png'); /* icon's coordinates in the squad */ background-position: -20px 0; }

Sprites method is efficient and manageable when handling multiple icons.

Advanced Structures: More freedom with <button> and <img>

<button class="button-with-img-icon" type="button"> <img src="icon.png" alt="Icon Description" height="16" width="16"> Say it out loud </button>

Then arrange the children (icon & text) using CSS flexbox or CSS grid, until they say 'cheese'!

Go beyond: Enhance your button design

Afterwards with Pseudo-elements

.icon-btn:after { /* Bob Ross painted an icon right here */ content: url('icon.png'); /* Icon's luxury spot in the button */ position: absolute; right: 5px; top: 50%; /* Center it, 'cause it's VIP */ transform: translateY(-50%); }

This addition opens up possibilities for hover effects and dynamic changes. It's CSS-only magic.

Cross Browser Challenge: Make Opera sing the same tune as Chrome

Bear in mind, <input type="button"> and <button> may sing different tunes in different browsers. Test to ensure they all sing Kumbaya.

Accessibility: Because every click matters

Ensure your buttons are reachable, by offering alternative text for the images and the appropriate ARIA attributes. Offer the welcome mat to everyone.