如何通过css设置一张背景图片自动水平垂直居中呢?可以通过css提供的background-position: center进行设置。设置代码:.bg-img{ height: 100vh; width: 100%; background-image: url(img/car.jpg); background-repeat: no-repeat; background-position: center; }
方法/步骤
1
打开前端开发工具,新建一个html代码页面
2
在html代码页面上创建一个用于设置背景颜色的div标签,然后给这个标签添加上class = 'bg-img'
3
设置背景图片。创建style标签,然后在标签里面对类为bg-img设置背景图片、图片不重复、宽、高的样式。样式代码:.bg-img{ height: 100vh; width: 100%; background-image: url(img/car.jpg); background-repeat: no-repeat; }
4
保存html代码,使用浏览器打开,这个时候会发现浏览器上的背景图片显示在左上角。
5
回到html代码页面,在bg-img类里添加background-position: center的属性。
6
保存html代码后重新刷新浏览器,这个时候会发现浏览器上的背景图片已经自动居中了。
下一篇:如何设置DIV居中