How can I have a transparent overlay and center with flex box?


I have a block element with a background image. I am attempting to:

  • Add a transparent gradient overlay on top of a background image
  • Center another block element using flexbox,

I have already achieved both of these independently of each other, see the CodePen as well as the images and code below.

Using the transparent overlay (with the child block HTML removed):

enter image description here

Centering the child block (with the overlay CSS removed):

enter image description here

However when I try and combine the effects, the flexbox stops working and the overlay is missing around the child block enter image description here

Here is my HTML

<div class="container">
  <p>title goes here</p>
</div> 

Here is my CSS:

.container {
  background: url("http://msue.anr.msu.edu/uploads/images/forest.jpg");
  height: 400px;
  width: 100%;
  box-shadow: inset 0px -4px 14px 0px rgba(50, 50, 50, 0.71);
  background-size: 100% auto;
  z-index: 0;
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.container p {
  display: block;
  color: red;
  text-align: center;
  font-size: 24pt;
  background-color: blue;
  z-index: 2;
}
.container:after {
  content: '';
  background: linear-gradient(135deg, #dc4225, #292484);
  width: 100%;
  height: 100%;
  opacity: 0.5;
  top: 0;
  left: 0;
  display: block;
  z-index: 1;
  position: relative;
}

How can I get the semitransparent overlay overlay and the flexbox happening at the same time?


Answers:


For .container:after, change position: relative to position: absolute.

Live, working example:

.container {
  background: url("http://msue.anr.msu.edu/uploads/images/forest.jpg");
  height: 400px;
  width: 100%;
  box-shadow: inset 0px -4px 14px 0px rgba(50, 50, 50, 0.71);
  background-size: 100% auto;
  z-index: 0;
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.container p {
  display: block;
  color: red;
  text-align: center;
  font-size: 24pt;
  background-color: blue;
  z-index: 2;
}
.container:after {
  content: '';
  background: linear-gradient(135deg, #dc4225, #292484);
  width: 100%;
  height: 100%;
  opacity: 0.5;
  top: 0;
  left: 0;
  display: block;
  z-index: 1;
  position: absolute;
}
<div class="container">
  <p>title goes here</p>
</div> 

Codepen Version: http://codepen.io/anon/pen/gpqxoo