Home >Web Front-end >JS Tutorial >How to set the image to center in javascript
Method: 1. Wrap the image with div and span; 2. Use setAttribute() to add "display:table;text-align:center" and "display:table-cell;vertical-align:middle" ;"style.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to center the image using javascript:
Build an HTML framework
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> div { width: 500px; height: 200px; border: green solid 1px; } </style> </head> <body> <div id="app"> <span id="img"> <img src="img/1.jpg" style="max-width:90%" / alt="How to set the image to center in javascript" > </span> </div> </body> </html>
Use the setAttribute() method to add an image centering style
var div=document.getElementById("app"); var img=document.getElementById("img"); div.setAttribute("style","display:table;text-align: center;"); img.setAttribute("style","display:table-cell;vertical-align: middle;");
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to set the image to center in javascript. For more information, please follow other related articles on the PHP Chinese website!