JS+CSS sets img to show only the vertical center of img in DIV

  • 2020-03-26 21:39:19
  • OfStack

Img is displayed in a Div. The width of Img is the same as that of Div, but the height is not fixed. Only the vertical center of Img is required to be displayed.

Example:
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201310/201310241544061.gif? 2013924154453 ">  

The original:
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201310/201310241544061.jpeg? 2013924154556 ">

Code implementation:
 
<div style="width: 190px; height: 100px; overflow: hidden;"> 
<img src="http://beijing.timeoutcn.com/UserFiles/Images/2013-10-21/20131021104840077cover-22-1.jpg" width="190px" style="vertical-align: middle;" 
onload="this.style.marginTop = (parseInt(this.parentNode.style.height) - this.height)/2 + 'px';this.style.marginLeft = (parseInt(this.parentNode.style.width) - this.width) /2 + 'px'" /> 
</div> 

(link: http://xiazai.jb51.net/201310/yuanma/picjz.rar)

Related articles: