Home > Enterprise >  How to keep the center of the background image in html css
How to keep the center of the background image in html css

Time:10-31

So i made a html page with background image of a person on it like this. I want to make it responsive, so that when I open the web on the phone, the person is on the center (shows the center of the image). For now the output shows the left part of the image like this. Is there any part in the css that i can change to make that happen?

CodePudding user response:

Change your HTML code like below. You may see the Link

<div class="imageDiv">
       <img class="imageClass" src="../yourfile/" />
</div>

Then try with the following CSS:

div.imageDiv {
    position:absolute;
    max-width:45%;
    max-height:45%;
    top:50%;
    left:50%;
    overflow:visible;
}
img.imageClass {
    position:relative;
    max-width:100%;
    max-height:100%;
    margin-top:-50%;
    margin-left:-50%;
}

CodePudding user response:

Using the image given in the question (which is a screenshot, but I assume contains most of the actual image) I think it may be possible that using just plain CSS without regard to exactly where the figure's head is in relation to the image dimensions will be good enough for your needs.

This snippet uses both background-size: cover - to ensure the whole of the element (in this case the body) is covered and background-position: center center - to get (roughly) the head in the center both vertically and horizontally.

It would be useful to check using your actual image rather than the mockup from the screenshot but hopefully this snippet shows the basic idea:

body {
  background-image: url(https://i.stack.imgur.com/E2Emo.jpg);
  width: 100vw;
  height: 100vh;
  background-size: cover;
  background-position: center center;
}
<body></body>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related