css

Add image to background using CSS

In CSS you can add an image to the background to an HTML element using the 'background' or 'background-image' property of CSS

/* using background proprty */
body {
    background: url('https://placeimg.com/640/480/arch'); /*this will add image to background */
}

/* using background */
body {
    background-image: url('https://placeimg.com/640/480/arch'); /*this will add image to background */
}

In the code snippet, we have added a background image to the body HTML element using the background and background-image property of CSS.

Remove repetition of the image

To disable repetition of the image to the element you can use the background-repeat property as below

.element {
   background-image: url('https://placeimg.com/640/480/arch');
   background-repeat: no-repeat;
}

Cover full part of HTML element

To cover the full part of the HTML element you can use the background-size property of CSS.

.element {
   background-image: url('https://placeimg.com/640/480/arch');
   background-repeat: no-repeat;
   background-size: cover;
}

Make Image 100% width and 100% height

You can assign values to the background-size property to make an image plot in a specific size.

/* PERCENTAGE - width 100%, height 100% */
.element {
   background-image: url('https://placeimg.com/640/480/arch');
   background-repeat: no-repeat;
   background-size: 100% 100%;
}

/* PX - width 500px, height 300px */
.element {
   background-image: url('https://placeimg.com/640/480/arch');
   background-repeat: no-repeat;
   background-size: 500px 300px;
}
Was this helpful?