Rohan Ghiya
Rohan Ghiya

Reputation: 21

Fix position of button on image

I'm trying to fix a button over a specific spot in an image. Is there any way to merge the button with a specific part of an image? This is what I have so far I have the button exactly where I want it but when the browser is stretched or zoomed in, the button doesn't stay.

Here's the JSFiddle of what I have https://jsfiddle.net/vkfLywna/1/

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            .container {
                position: absolute;
                width: 100%;
                max-width: 400px;
            }

            .container img {
                width: 200%;
                height: auto;
            }

            .container .btn {
                position: relative;
                top: -330px;
                left: 96px;
                transform: translate(-50%, -50%);
                -ms-transform: translate(-50%, -50%);
                background-color: #555;
                color: white;
                font-size: 6px;
                padding: 4px 10spx;
                border: none;
                cursor: pointer;
                border-radius: 5px;
                text-align: center;
            }

            .container .btn:hover {
                background-color: black;
            }
    </style>
</head>
<body>

    <div class="container">
        <img src="doc.png.png" alt="img" style="width:100%">
        <button class="btn">Button</button>
    </div>

</body>
</html>

Upvotes: 2

Views: 1814

Answers (2)

Kevin Boucher
Kevin Boucher

Reputation: 16675

Wrap the img and the button with a div and position them accordingly:

.img-container {
  border: solid red 1px;
  display: inline-block;
  position: relative;
}

.img-container button {
  position: absolute;
  top: 50px;
  left: 50px;
}
<div class="img-container">
  <img src="http://via.placeholder.com/350x150">
  <button>Click here</button>
</div>

Upvotes: 2

Mirza
Mirza

Reputation: 1

the .container has to be position:relative and .btn position:absolute. Than you can positionate the button with top and left in the container, use % instead of px to stay responsive.

you don't need transform for this.

.container {
  position:relative;
  width:100%;
}

.container img {
  width:100%;
  height:auto;
}

.container button {
  position:absolute;
  top:20%;
  left:20%;
}
<div class="container">
  <img src="https://dummyimage.com/600x400/ff00ff/fff">
  <button>
    Click
  </button>
</div>

Upvotes: 0

Related Questions