dungey_140 dungey_140 - 2 months ago 10
CSS Question

Overlay 2 text elements, whilst vertically centering

I am trying to overlay two pieces of text, directly on top of one another to create a layered effect, whilst also trying to vertically centre them in the parent. To vertically centre, I am using a ghost pseudo element as outlined in this post, which I find to be the most reliable method when centring in a parent whose height is variable.

As you can see in the fiddle below, the .bg-text element is vertically centered, but the .text-wrapper element is forced to sit below the parent, so it appears this method of vertically centring does not allow for more than one centered element?

HTML

<figure>
<div class="bg-text">BACKGROUND TEXT</div>
<div class="text-wrapper">
<h3>Overlay This</h3>
<h4>And this!</h4>
</div>
</figure>


CSS

figure {
position: relative;
overflow: hidden;
float: left;
width: 100%;
height: 200px;
background: red;
}
figure::before {
content: "[BEFORE]";
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em;
}
/* Background text */
.bg-text {
display: inline-block;
vertical-align: middle;
width: 80%;
color: green;
text-align: center;
}
/* Text */
.text-wrapper {
display: inline-block;
vertical-align: middle;
width: 80%;
text-align: center;
color: blue;
}


FIDDLE

Answer

Flexbox and absolute positioning can do that:

* {
  margin: 0;
  padding: 0;
}
figure {
  position: relative;
  height: 200px;
  background: red;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}
/* Background text */

.bg-text {
  width: 80%;
  color: green;
  text-align: center;
}
/* Text */

.text-wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 255, 0, 0.25);
  width: 80%;
  text-align: center;
  color: blue;
}
<figure>
  <div class="bg-text">BACKGROUND</div>
  <div class="text-wrapper">
    <h3>Overlay This</h3>
    <h4>And this!</h4>
  </div>
</figure>