cssimagebordercenterweb-frontend

How to center the image in the div after adding the borders around the image?


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 .


Solution

  • 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>