How to Center Background Image within div?
you can be fixed the center background image within div in CSS. it is very simple to use CSS property background-position: center; for center or posting the background image, you will use CSS property which is for background-position
you can fix images according to your requirement. first thing is that you will be given the path (URL) of background images which you want to use for the background image background-image: URL(‘images/pic.png’);
Here, in the bracket is the image path where stored in your system, you can choose image extension anyone such as .png, .jpg, .jpeg, etc.
if you want to entire div to be filled with image background, no extra space you must use background-size: cover; Another way I tell to you if you want to the entire image to show in the website without image cut off or stretched
you will use background-size: contain; I will suggest you always use this code for center background image within div
1 2 3 |
.your_class { background: url(image.png) no-repeat center /cover; } |
if you don’t want to use background image repeated means in X and Y direction you will use no-repeat use also use below CSS property code for center background image within div
1 2 3 4 5 6 |
.your_class { background-image: url(image.png); background-position: center; background-size: cover; background-repeat: no-repeat; } |
the background-size is a new property, the cover used for fill background sizing and positioning in windows desktop background.
1 2 3 4 5 6 7 |
.your_class or #class_id { background-image: url(url); background-size: 100%; width: 700px; height: 300px; margin: 0 auto; } |
Here, margin: 0 auto; will be used to makes it center horizontally within the div. another situation such as if you need in the website the image horizontally centered but on top vertically.
use this CSS property background-position: 50% 0%;
Note:- you know in CSS property, that you never need any unit when the value is 0. In CSS background-position defined in the Horizontal position which is X-axis and Vertical Position will be Y-axis.