davide l davide l - 4 months ago 7
CSS Question

Center an button with respect to an image CSS

I need a page where centered in the middle there is an image and inside of it there is button. What I am not able to achieve is to force the button to remain in the same position when the browser window is re-sized.
This is the page:
http://jsfiddle.net/afg5wrLz/

The HTML code:

<div id="MyImage">
<img id="theImage" src="http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg">
<button id="myButton">Start Here</button>
</div>


The CSS:

#MyImage{
position: relative;
}

#theImage{
position: relative;
margin-left: auto;
margin-right: auto;
margin-top: 20px;
display: block;
width: auto;
height: auto;
max-width: 400px;
}
#myButton{
position: absolute;
left: 0px;
top: 0px;
}


Now if you re-size the window you will see the problem; the left coordinate of the button is related to the window and not to the image so when you re-size the window the button moves while I want it to remain in the same position in the image.
To have a better idea of what I need head to http://www.whatsapp.com/ and look at the behavior of the Download WhatsApp button or the text "Simple. Personal ..." if you re-size the window you will see they remain in the same position with respect to their background image which remains centered in the screen as the width changes.
I would like to know what I need to change in my code to achieve that result

Answer

Here is a centered image with a button inside following the image http://jsfiddle.net/afg5wrLz/2/

The HTML

<div id="MyImage">
    <img id="theImage" src="http://www.jpl.nasa.gov/spaceimages/images/mediumsize/PIA17011_ip.jpg" />
    <button id="myButton">Start Here</button>
</div>

The CSS

#MyImage {
    position: relative;
    margin: 20px auto 0;
    width: 100%;
    max-width: 400px;
}
#theImage {
    display: block;
    position: relative;
    width: 100%;
}
#myButton {
    position: absolute;
    left: 0px;
    top: 0px;
}
Comments