Search code examples
htmlcssimagecenter

CSS - Center Image at all times


I have an image that I am using inside a Div.

I was wondering how I could center the image both vertically and horizontally at all times.

At the moment, when I stretch it, it seems to be stretching from the top left corner, is there a way I could have it centered at all times.

I have searched the web and tried various things but can not seem to get it to work.

this is my html:

<div class="container"></div>

here is my css:

.container {
    width: 100%;
    height: 75vh;
    background-image: url("https://i.sstatic.net/2OrtT.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: 50% 50%;
}

Any help or advice is appreciated, thank you in advance.

EDIT you can see that when I stretch the browser, it seems to be stretching from the left, i want to be able to have the Image centered so it stretches from all sides equally*


Solution

  • I got the solution..!

    Here is your html file :

    <div class="container"></div>
    

    CSS file :

    .container {
    width: 100%;
    height: 75vh;
    position: absolute;
    margin: auto;
    background-image: url("https://i.sstatic.net/2OrtT.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: 50% 50%;
    top: 0;
    left: 0;}
    

    Here is working demo