htmlcssimagebackgroundbackground-image

How can i add padding to an image?


I have an image and want it to have some space from the borders of the <div> it's contained in. I have tried adding padding but the image still fills the whole <div> and seems to ignore the padding values I've added.

This is what the image looks like:

enter image description here

#railwayblock {
  height: 500px;
  border-style: solid;
  border-width: 10px;
  border-color: green;
  padding-right: 50px;
  padding-left: 50px;
  background-image: url("https://via.placeholder.com/800");
  background-size: cover;
}
<div id="railwayblock"></div>

I want it to have some space from the borders of the div that it's contained in as I have mentioned before.


Solution

  • background-size:cover; will make the background image always cover everything, including the padding space.

    You can either use a regular image (i.e. <img> tag) instead of the background image as child of a parent element which has the padding, or you can use a background image in a div and wrap a parent element around that one which has the padding. In this case you need height settings for both, with the height of the inner element being smaller by the amount of the top and bottom padding.