0

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.

Nhan
  • 3,520
  • 6
  • 29
  • 37
JoaMika
  • 1,634
  • 4
  • 26
  • 57

2 Answers2

1

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>
Racil Hilan
  • 23,737
  • 12
  • 48
  • 51
0

Option 1: Position Absolute and the translate -50% method

body {
  margin: 0; padding: 0;
}
.outer {
  position: relative;
  background-image:url(http://i.imgur.com/55PnNyJ.jpg);
  height:100vh;
  background-size: cover;
  background-repeat: no-repeat;
}
.centered {
  position: absolute;
  top: 50%; left: 50%;
  transform: translateY(-50%) translateX(-50%);
  display: inline-block;
  color: hsla(0, 0%, 100%, 0.4);
  background-color: hsla(0, 0%, 0%, 0.4);
}
<div class="outer">
  <div class="centered">I'm (almost) On A Boat</div>
</div>

fiddle

https://jsfiddle.net/Hastig/j7rgjspt/2/


Option 2: Flexbox and justify-content/align-items center

body {
  margin: 0; padding: 0;
}
.outer {
  display: flex;
  justify-content: center;
  align-items: center;
  background-image:url(http://i.imgur.com/55PnNyJ.jpg);
  height:100vh;
  background-size: cover;
  background-repeat: no-repeat;
}
.centered {
  display: inline-flex;
  text-align: center;
  color: hsla(0, 0%, 100%, 0.4);
  background-color: hsla(0, 0%, 0%, 0.4);
}
<div class="outer">
  <div class="centered">I'm (almost) On A Boat</div>
</div>

fiddle

https://jsfiddle.net/Hastig/j7rgjspt/1/

Hastig Zusammenstellen
  • 4,082
  • 3
  • 31
  • 45