Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use an image and text inside a <button>

Tags:

html

css

Im trying to have a button with format like I have in my image 1.

Where I have a div with background red at left, and inside this div I have an image, and I want this image aligned at center of my div.

And then I have the text of my button at right of my red div.

Image 1:

enter image description here

But What Im having is this:

Image 2

enter image description here

I dont have my image at center of my red div, and my button text is stucked in my div.

Do you see what Im doing wrong?

This is my fiddle with issue Im having: http://jsfiddle.net/nXuU2/2/

This is my html

<button class="btn">               
    <div id="btn_container"><img  src="http://placehold.it/30x30" width="30" height="30"/></div>
    <span>Button link 1</span>
</button>

And my CSS:

   .btn
{

    position: relative;
    width: 200px;
    height: 60px;
    margin-bottom:20px;
    padding: 0 10px;
    text-align: left;

    font-size: 16px;
    color: #333;
    background:gray;
}

#btn_container
{
    width:40px;
    height:40px; 
    border-radius:5px;
    background:red; 
    float:left;
}

.btn img 
{  
    margin-right: 10px;
    vertical-align:middle;
}


.btn span
{
    display:inline-block;
    width: 120px;
    vertical-align:middle;
}
like image 613
UserX Avatar asked Jul 25 '14 16:07

UserX


People also ask

Can I use IMG inside button?

You can include an <img> element inside your <button> element to display the image on the button.

How do I put text inside a button in HTML?

The exact solution depends on what content exactly is placed into the button, but the general idea is: Use a <button> element. Place a block element inside (a <div> will do fine) Give the block element bottom padding and put your text inside it.


1 Answers

Just playing with CSS positioning here, make your div with the red background position: relative; and use absolute for your img tag

Demo

.btn img {  
    left: 50%;
    margin-left: -15px; /* 1/2 of total width of your img */
    top: 50%;
    margin-top: -15px; /* 1/2 of total height of your img */
    position: absolute;
} 

Demo 2 (Alternate way to do this, you won't need CSS positioning)

In the Demo 2, you won't need CSS positioning, just remove margin-right from .btn img and use text-align: center; on #btn_container, and lastly, apply margin-top to .btn img


I don't think that you will need a wrapping element for background-color, just apply to img tag, so if you don't want to use your wrapping element than refer the solution below ..

CSS

.btn img {  
    display: inline-block;
    vertical-align: middle;
    background: #f00;
    padding: 5px;
    border-radius: 5px;
}

HTML

<button class="btn">               
    <img  src="http://placehold.it/30x30" width="30" height="30"/>
    <span>Button link 1</span>
</button>

Demo 3

like image 67
Mr. Alien Avatar answered Oct 29 '22 12:10

Mr. Alien