Reputation: 1038
I've written simple webpage with javascript, which attempts to scale an element from the centre of the page over time after a click. It works fine for the svg element I tested.
But when I use an image, it starts off outside of the div, (which is centred) and slowly converges towards it as it gets bigger, after which it is centred as it should be. The only results I can find are related to overflow settings, but even with overflow set to hidden the image is still outside of the div and visible. The div is the first thing to be resized, so it is always big enough for the image.
Could it be because of the small size values I am using, or is it a problem with my code?
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin:0;
}
#maindiv {
position:absolute;
background-color:#141414;
width:100%;
height:100%;
overflow: hidden;
}
#face {
width:109px;
/* height: auto !important; */
}
#facediv {
position: absolute;
top: 50%;
left: 50%;
}
</style>
<script>
function sizeUpdate (elem){
var sf = 1
function frame(){
sf++ <!-- increment scale factor
var fwidth = 0.1;
var scaledwidthface = (fwidth * sf); <!-- scaled width - width-constant*scale-factor
var face_var =document.getElementById("face");
var facediv_var = document.getElementById("facediv");
facediv_var.style.width = ""+scaledwidthface+"px"; <!-- set containing div to same width as object
facediv_var.style.marginLeft = ""+(-1 * scaledwidthface/2 )+"px"; <!-- set the container div to x-offset half object-width (centres horizontally)
face_var.style.width = ""+scaledwidthface+"px"; <!-- set width of object
var face_ht = face_var.clientHeight; <!-- get integer-form of object height (?)
facediv_var.style.height = ""+face_ht+"px"; <!-- set container div to same height as object
facediv_var.style.marginTop = ""+(-1*face_ht/2)+"px"; <!--set container div y-offset half object-height (centres vertically)
if (sf == 500)
clearInterval(id) <!--stop when incr reaches this maximum
}
var id = setInterval(frame, 50)
}
</script>
</head>
<body>
<div id="maindiv" onclick="sizeUpdate(this.children[0])">
<div id="facediv">
<img id="face" src="http://goo.gl/6xLiC">
</div>
</div>
</body>
</html>
Upvotes: 1
Views: 137
Reputation: 78540
Your issue is coming from the fact that images default to inline display rather than block. This means that images carry over the attributes of letters and words (font-size and line-height). The discrepancy you were seeing (illustrated in this fiddle) can be corrected by simply applying the following display:block
rule
#facediv img {
display:block;
}
I should have noticed sooner :P
EDIT: Out of morbid curiosity, I made the equivalent with the image still as an inline element setting the line height and font sizes to 0px. See it working in this demo
Upvotes: 2