Joanna Mikalai Joanna Mikalai - 3 months ago 8
CSS Question

Center div in middle of backround image across all screen resolutions

I am using this code to display a background image that takes the full vertical height of the browser.

<div id="outer"></div>


CSS

#outer {
background-image: url(https://www.mydomain./image.jpg);
height: 100vh;
background-size: cover;
background-repeat: no-repeat;
}


I am looking to place a div inside, which is both vertically and horizontally centered in the middle of the image for all screen resolutions.

So far I have been unsuccessful with everything I tried. This needs to be supported by majority of browsers.

Answer

Set the height and width for the inner div, then use margin: auto to center it horizontally, and padding: calc(50vh - 10px) 0 to center vertically. The 10px must be half of the height of your inner div. Try this:

#outer {
  background-image: url('http://placehold.it/100x100');
  height: 100vh;
  background-size: cover;
  background-repeat: no-repeat;
}
#inner {
  color: red;
  width: 100px;
  height: 20px;
  margin: auto;
  text-align: center;
  padding: calc(50vh - 10px) 0;
}
<div id="outer">
  <div id="inner">test</div>
</div>