Search code examples
htmlcssimagebuttonresolution

resize the image of button background relative to screen resolution in HTML with CSS


I have a button with a image as a background and I would like to resize the image size depending on screen resolution. For the images, I use width:100%, but in this case, if I use it for the button, the button size adjust to the screen resolution, but not the image it uses as a background. What can I do so the image resize the same way as the button?

<!DOCTYPE html>
<html>
<body>
  <button class="dog"><img src="pictures/dog.png" ></button>
  <style>
  .dog {
    position:absolute;
    width:100%;
    left:1%;
    top:6%;
  }
</style>
</body>
</html>

Solution

  • You can remove the image inside your <button> element and set the image as a background to your button instead. Use CSS background properties like background-size to make the background automatically fit your button.

    .bill {
      width: 180px;
      height: 80px;
      background: url("https://www.fillmurray.com/640/360");
      background-position: center;
      background-size: cover;
      color: floralwhite;
      font-weight: bold;
      font-size: 1.4em;
    }
    <button class="bill">Bill Me!</button>