I need to shift an image to the right by adding pixels to its current left position. The challenge arises when the image, positioned absolutely, goes back to its nearest relative parent (the container) and creates a strange visual effect.
Within my flex container, I have an image and a div both centered using the justify-content: center; property.
HTML code:
<button type="button" onclick="moveImage()">Move image</button>
<div id="container">
<div id="left" class="block">Left</div>
<div id="center" class="block">
<img id="image" src="https://appharbor.com/assets/images/stackoverflow-logo.png" alt="stackoverflow">
</div>
<div id="right" class="block">Right</div>
</div>
CSS code:
html, body{
width: 100%;
height: 100%;
}
#container{
display: flex;
height: 100%;
}
.block{
flex: 1;
}
#left{
background-color: red;
}
#center{
position: relative;
display: flex;
background-color: yellow;
justify-content: center;
}
#right{
background-color: orange;
}
#divCentered{
width: 50%;
height: 100px;
background-color: brown;
}
Javascript code:
$( document ).ready(function() {
var divParent = document.getElementById('center');
var div = document.createElement("div");
div.setAttribute("id", "divCentered");
divParent.appendChild(div);
});
function moveImage(){
$("#image").animate({
left: "+=300px"
}, 1000);
}
Visit this JSFiddle link to see the issue with the image shifting behavior.
If you know a way to prevent the image from reverting to its parent and instead continue to add pixels in its current position, your advice would be greatly appreciated! Here's a big thanks in advance!