mbsff
mbsff

Reputation: 55

How to position button relative to parent?

I'm having a problem with absolute positioning in my web page:

I want to position a button relative to its parent and this is what I did:

.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 0px;
  left: 0px;
}

.button {
  height: 55px;
  width: 180px;
  background-color: transparent;
  border-color: transparent;
  background: url(Button.png);
  background-size: 100% auto;
  background-repeat: no-repeat;
}
<div class="parent" align="middle">
  <img src="http://via.placeholder.com/1900" width="1900px" />
  <div class="child">
    <button class="button">Button</button>
  </div>
</div>

This code makes the button have its position relative to the window and not to the image in which it is supposed to be, so when i zoom out or in the button moves inside the image, instead of having the same relative position.

Upvotes: 2

Views: 2836

Answers (2)

Deep Sharma
Deep Sharma

Reputation: 3473

i guess this is what you want to achieve

here is the solution to your problem...

below is the updated css:

   .parent {
        position: relative;
   }
   .child{
        position: absolute;
        top: 0px;
        left:0px;
   }
   .button {
       height: 55px;
       width: 180px;

       background-size: 100% auto;
       background-repeat: no-repeat;
   }

Upvotes: 3

Dion Verhelst
Dion Verhelst

Reputation: 3

It seems that the positioning didn't work the way you want it to. And since you only wanted the image to be centered I did the following. I removed the position from the parent and changed the position on the image to relative. Then I positioned the button relative to the image. Try this:

HTML

<div class="parent">
    <img src="background.png" width="400px" />
    <div class="child">
        <button class="button"></button>
    </div>
</div>

CSS

.parent {
    text-align:center;
}
.child {
    position: relative;
}
.button {
    height: 55px;
    width: 180px;
    background-color: transparent;
    border-color:transparent;
    background: url(Button.png);
    background-size: 100% auto;
    background-repeat: no-repeat;
    position:absolute;
}

JSFiddle

Upvotes: 0

Related Questions