I can't get an image positioned properly from JavaScript using img.style.top and img.style.left, it's always showing on top left, unless I use the CSS. Please help this newbie.
<---css file--->
.imgTable {
position: relative;
z-index: -1;
}
.imgDeal {
position: absolute;
transform: scale(.5);
//top: 60px; // --- this works ---
//left: 470px; // --- this works ---
z-index: 1
}
<--- html file --->
div class="table-body">
<div class=imgTable>
<img src="images/table.png">
<div id="imgDeal" class="imgDeal"> </div>
</div>
</div>
<--- JS file --->
var img = document.createElement('img');
img.src = "images/deal.png";
img.style.top = "60px"; // --- this does not work ---
img.style.left = "470px"; // --- this does not work ---
document.getElementById('imgDeal').appendChild(img);
Your JavaScript code adds the inline style to your newly created img element but not to your .imgDeal div element. Your newly created img element is not positioned absolutely or fixed, so the top
and left
css rules have no effect.
One possible solution can be changing your CSS code from
.imgDeal {
position: absolute;
transform: scale(.5);
z-index: 1
}
to
.imgDeal img {
position: absolute;
transform: scale(.5);
z-index: 1
}
and optionally giving your .imgDeal div element a fix width and height.