Reputation: 2045
I would like to have a button with 100% of an image's width and height without specifying the width and height on the button.
eg: If I change the image, the button size should be changed dynamically as well according to the size of the image
Note: The button size should be exactly the image size without stretching/distorting/enlarging/shrinking the image. If I change the image to 300px * 200px, the button size should be 300px * 200px as well.
Is it possibly to be done with css alone?
#rock {
width: 150px;
height: 150px;
background-image: url(https://i.imgur.com/CeJU3mO.png);
background-repeat: no-repeat;
}
<button id="rock"></button>
Upvotes: 1
Views: 3072
Reputation: 78676
You can add the image with a pseudo element and make it hidden to hold the size.
#rock {
background-image: url("https://i.imgur.com/CeJU3mO.png");
background-repeat: no-repeat;
padding: 0;
}
#rock:before {
content: url("https://i.imgur.com/CeJU3mO.png");
visibility: hidden;
}
<button id="rock"></button>
Apart from background, you can also use inline image inside the button.
<button id="rock"><img src="https://i.imgur.com/CeJU3mO.png" alt="Button"></button>
Otherwise use <input type="image" src="...">
instead.
input[type="image"] {
outline: 1px solid; /*demo*/
}
<input type="image" src="https://i.imgur.com/CeJU3mO.png">
Note, that image has some blank edges by default.
Upvotes: 2
Reputation: 53674
You can't make an element match a background-image
's size without explicitly setting the element height to match the image.
You can use <input type="image">
which is a graphical submit button, and the input
's size will match the dimensions of the image.
Upvotes: 0