1

I want to be able to have a button that is positioned relative to an image. I made a jsfiddle for what I am trying to do.

https://jsfiddle.net/a1e1vb1n/

My expectation is that the button would move with the image, but as you can see it does not =(

HTML:

<div id="container">

<div id="parent">
    <img src="http://i.imgur.com/wsNrRVQ.jpg" width=200px height=200px>
</div>

<div id="child">
    <button>
    Click Me
    </button>
</div>

CSS:

#container {
  position: relative;
}

#parent {
  position: absolute;
  left: 200px;
}

#child {
  position: absolute;
}
salih kallai
  • 879
  • 2
  • 13
  • 34
user3591815
  • 25
  • 2
  • 6
  • How can you position an element relative to another when you have specified it absolute in the css? –  Mar 13 '16 at 07:07
  • Possible duplicate of [Css Sibling Absolute Positioning](http://stackoverflow.com/questions/10624771/css-sibling-absolute-positioning) – André Lucas Mar 13 '16 at 07:07
  • 1
    the button should actually move along with the image if the button and the image are in the same div... – Jones Joseph Mar 13 '16 at 07:08

3 Answers3

1

try this-

<div id="container">

 <div id="parent">
    <img src="http://i.imgur.com/wsNrRVQ.jpg" width=200px height=200px>
    <div id="child">
      <button>
      Click Me
      </button>
    </div>
 </div> 
</div>
LoopCoder
  • 172
  • 6
0

When you say the button should be positioned relative to the image, you have to place the button inside the div that holds the image and give the button a relative position.

Updated Fiddle : https://jsfiddle.net/a1e1vb1n/2/

user3613129
  • 411
  • 4
  • 13
0

The relevant changes are as follows:

#parent {
  position: absolute;
  left: 200px;
  display: flex;
}

#img {
  display: block;
}

#button {
  display: block;
  height: 20px;
  width: 50px;
} 
  • Moved the button into #parent and gave it an id of #button and dimensions of 50 x 20px for simple stability.

  • Made #img and #button display: block for stability.

  • Removed #child since it's no longer needed.

  • Made #parent a flex container to control the positioning of it's children #img and #button

  • If you want #button to be above or below #img:

    • Above #img: add flex-direction: column to #parent

    • Below #img: add flex-direction: column-reverse to #parent

Fiddle

Snippet

#container {
  position: relative;
}

#parent {
  position: absolute;
  left: 200px;
  display: flex;
}

#img {
  display: block;
}

#button {
  display: block;
  height: 20px;
  width: 70px;
}
<div id="container">

  <div id="parent">
    <button id="button">
      Click Me
    </button>
    <img id="img" src="http://i.imgur.com/wsNrRVQ.jpg" width=200px height=200px>
  </div>



</div>

See this article for flexbox

zer00ne
  • 41,936
  • 6
  • 41
  • 68