skip to Main Content

html and CSS coding
Preview

As you could see the pics I’ve added, I’ve centered the DIV at the center of Web page, and centered the image and texts inside DIV at the center of Webpage too.

The issue is that when I add the 5px white borders around the image, the right side of image gets out of the DIV. I understand It’s because of adding the borders because without the borders, the image is centered correctly.

So Is there a way to add the 5px borders around all sides but also containing image at center inside DIV without making the right side of image getting out?

P.S: I’m still a beginner, So forgive me if my question sounds little bit easy or strange.

I’ve tried to calculate the image by pixels in width relative to the size of the DIV so I could center the image after adding the borders around the image and still maintaining image inside DIV.

But I’m asking, Is it possible that while working at medium-large projects , Should I always calcualte how many pixels in width should I enter plus adding borders pixels to center image correclty?

If It’s the only way, sure no problem, I’ll do the math.
I’m just asking If there is a better, more efficient way to do this task in the future .

2

Answers


  1. You should generally use this property when writing CSS to reset default CSS styles browser applies to certain elements.

    *, *::after, *::before {
        box-sizing: border-box;
    }
    

    Read about CSS Box Sizing W3Schools

    Also, It is a good practice to wrap your image elements in a container div for themselves, something like this

    <div>
        <div class="img-container">
            <img src="#" alt="website banner" />
        </div>
        <h1>Never Give up, Keep pushing</h1>
        <p>No matter what happens, always keep pushing forward</p>
    </div>
    
    Login or Signup to reply.
  2. If you want to ensure that the image stays within the bounds of the div, you can use:

    img {
      object-fit: contain;
    }
    

    this ensures that the size of the image does not exceed the bounds of its parent element. And for the future, you should set the border-sizing property to border-box for all elements, with:

    *, *::before, *::after {
      box-sizing: border-box;
    }
    

    This property changes the way elements are rendered, such that the borders and padding are not added onto the element. It instead takes part of the element’s dimensions for these properties.

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