How to center the image in the CSS file: first create an HTML sample file; then introduce a background image; and finally use the "background-position" attribute in CSS to center the image.
The operating environment of this article: windows7 system, HTML5&&CSS3 version, DELL G3 computer.
CSS method to center the background image
It’s actually very simple. The background-position property in CSS can achieve the horizontal and vertical center alignment of the background image, as follows We use a simple code example to introduce how the background-position attribute sets the background image to be centered.
We first use the background attribute to display the background image:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>背景图片居中</title> <style> *{margin: 0;padding:0;} .demo{ width: 400px; height: 300px; margin: 50px auto; border: 1px dashed #000; background-image:url(1.jpg) ; background-size:200px 160px ; background-repeat:no-repeat ; } </style> </head> <body> <div class="demo"> </div> </body> </html>
Rendering:
Recommendation: "css video tutorial》
Next let’s take a look at how to set the background-position attribute:
1. Background-position uses pixels to set the background image to be centered (know the size of the background image)
In the example, the lower right corner of the background image coincides with the center of the demo box. If you want to center the background image, you need to make the center of the background image coincide with the center of the demo box. You need to move the background image half of the height downwards and to the right. Move half the width. Therefore, by adding the following code to css, you can center the background image
background-position: 100px 70px; /*Half the width, half the height*/
Rendering:
2. Background-position uses 50% to set the background image to be centered, which is very convenient.
background-position:50% 50%;
3 , background-position uses center to center the background image, which is very convenient. (The second center can be omitted)
background-position:center center;
The above three setting methods of background-position can all achieve the centering of the background image. The third of the background-position attribute One value sets the horizontal position, and the second value sets the vertical position; you can decide which method to use depending on the situation. I hope it will be helpful to everyone's study.
The above is the detailed content of How to center images in CSS files. For more information, please follow other related articles on the PHP Chinese website!