skip to Main Content

i have an image inside a div and want the image to have some space from the borders of the div its 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, any help please, here’s the code in the html file

<body>
<div id="railwayblock">
</div>
</body>

here’s the css file

#railwayblock{
height: 500px;
border-style: solid;
border-width: 10px;
border-color: green;
padding-right:50px;
padding-left:50px;
background-image: url("animated_train.jpg");
background-size:cover;

}

this is what the image looks likeenter image description here

i want it to have some space from the borders of the div that its contained in as i have mentioned before.

2

Answers


  1. 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
    }
    
    Login or Signup to reply.
  2. To add padding around the image inside the #railwayblock div, you need to set the padding property directly to the #railwayblock div itself, not to the background-image.

    Here’s how you can modify your CSS:

    #railwayblock {
        height: 500px;
        border: 10px solid green;
        padding: 50px; /* Add padding around the content */
        background-image: url("animated_train.jpg");
        background-size: cover;
    }

    By setting padding: 50px;, you add 50 pixels of padding around all four sides of the #railwayblock div, creating space between the border and the content (including the background image).

    With this adjustment, the image inside the #railwayblock div should now have space from the borders of the div as specified by the padding values. Adjust the padding values as needed to achieve the desired spacing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search