Sean Peterson Sean Peterson - 13 days ago 9
CSS Question

centering absolute text over image with darkened background

Ok so I need to position text overtop of a slider and have a darkend background behind the text so that it's readable. Simply using text-align: center doesn't work in this instance as the darkened background takes up the entire page width

http://codepen.io/SeanPeterson/pen/WoERXb?editors=1100

.wrapper h4{
position: absolute;
top: 50%; /* Would love to get rid of this! */
color: red;
margin: auto;
width: 100%;
background: rgba(0, 0, 0, 0.5);
padding: 1rem;
}
.wrapper{
position: relative;
width: 100%;
text-align: center;
}


So the only solution to this that I could think of was to position it using the left and right css properties. So in this case I put left and right to 40% each.

http://codepen.io/SeanPeterson/pen/WoERXb?editors=1100

.wrapper h4{
position: absolute;
top: 50%;
color: red;
margin: auto;
left: 40%;
right: 40%;
background: rgba(0, 0, 0, 0.5);
padding: 1rem;
}


The problem though is that this has to be a dynamic page and work for all of the different screen sizes. Using this method I would have to code in the values for all the screen sizes I can come up with ... just seems like it's not an eloquent solution to me. Plus I'm also running into the issue now where the absolute text overlaps other elements if the user increases page zoom.

I'm still a noob so I'm hoping there's a better way to do this?

Thanks Guys!

Answer

Add the text inside your h4 in a span:

<h4><span class=text>SOME TEXT</span></h4>

And then:

.text{
    background: rgba(0, 0, 0, 0.5);
    padding: 1rem;
 }

And you can remove the padding from h4 so h4 would be:

.wrapper h4{
  position: absolute;
  top: 50%; /* Would love to get rid of this! */
  color: red;
  margin: auto;
  width: 100%;
  background: rgba(0, 0, 0, 0.5);
 }

Here is a fixed version of your pen