1、新建一个html文件,在这个html文件上创建一个<img>标签,然后对这个标签设置图片路径,最后为这个标签添加一个类(案例中类为:img-center)
2、对img-center类设置样式。1.设置positon定位为绝对定位,上下左右的距离都为:0;2.设置这个类的外编辑为:auto。代码:.img-center{position: absolute;top: 0;right: 0;bottom: 0;left: 0;margin: auto;width: 300px;}
3、保存html文件后,使用浏览器打开,即可看到图片自动居中。
4、所有代码。可以直接复制所有代码,粘贴后运行即可看到效果。所有代码:<!DOCTYPE html><html><head媪青怍牙><meta charset="UTF-8"><title>图片自动水平垂直居中</title><style type="text/css">.img-center{position: absolute;top: 0;right: 0;bottom: 0;left: 0;margin: auto;}</style></head><body><img src="images/22.png" alt="" class="img-center"/></body></html>