How to Add Padding to a Background Image in CSS?

Using CSS padding property, we can very easily apply padding around HTML elements. But, what if you have set a background image to an element and then you want to apply some padding on it?

Something like this:

If you directly try to add padding to an element which has a background image, it is not going to work. To make this work, we have to take the help of the background-clip property.

The background-clip property specifies how far an element’s background image should extend within the element. By default, this property is set to border-box.

It means that the background image extends up to the border of the element by default. This is the reason that directly applying padding on the background image does not work.

So, If you want to add padding to the background image, you have to set the background-clip property to content-box so that the background image could extend only up to the element’s content.

Here is a fully working example that applies a 10px padding around the background image:

Example:

div{
    width: 250px;
    height: 250px;
    border: 2px solid red;
    background-image: url('images/coffee.jpg');
    background-clip: content-box;
    background-size: cover;
    padding: 10px;
}

Here is one more example with a rounded background image:

Example:

div{
    width: 250px;
    height: 250px;
    border: 2px solid red;
    border-radius: 50%;
    background-image: url('images/coffee.jpg');
    background-clip: content-box;
    background-size: cover;
    padding: 10px;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.