1

I am trying to create a white box centered, both horizontally and vertically, within a div with a background image.

I have managed to center it horizontally as seen below in the "center"-class, but not vertically. I have tried to set "bottom" for the "filter-box"-class to the desired value and tried to use line-height and vertical align - all without the box even moving.

.image-container {
  background: url('stubbe.jpg') no-repeat fixed;
  height: 40em;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  line-height: 20em;
}

.filter-box {
  background-color: white;
  width: 500px;
  height: 100px;
  vertical-align: middle;
}

.center {
  margin: auto;
  width: 50%;
}
html
<div class="image-container">
  <div class="filter-box center">
  </div>
</div>
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
brun
  • 33
  • 3

2 Answers2

2

You can use display:flex and align-items: center in your parent element.

.image-container {
  display: flex;
  align-items: center;

  background: yellow no-repeat fixed;
  height: 40em;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  line-height: 20em;
}
.filter-box {
  background-color: white;
  width: 500px;
  height: 100px;
  vertical-align: middle;
}
.center {
  margin: auto;
  width: 50%;
}
<div class="image-container">
  <div class="filter-box center">
  </div>
</div>

I case of need you can center it horizontally with flex too, just add justify-content: center;

Jax-p
  • 7,225
  • 4
  • 28
  • 58
0

You could also use flexbox to quickly center the div by setting the outer container's display to be flex. This would also negate the need for the center class.

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('stubbe.jpg') no-repeat fixed;
  height: 40em;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  line-height: 20em;
}

.filter-box {
  background-color: white;
  width: 500px;
  height: 100px;
}
Connor Smyth
  • 317
  • 2
  • 8