CSS image in div ignoring padding

62 Views Asked by At

I have an image inside a div and want the image 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.

2

There are 2 best solutions below

0
Johannes On BEST ANSWER

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.

0
Alexxino On

What if you tried using an HTML img tag instead of background?

For example,

<body>
<div id="railwayblock">
  <img src='animated_train.jpg'></img>
</div>
</body>
#railwayblock {
  height: 500px;
  border: 10px solid green;
  padding: 0 50px;
}
#railwayblock > img {
  width: 100%;
  height: 100%;
  object-fit: cover
}