Pearson Pearson - 4 months ago 32
CSS Question

CSS3: Center Text (content) in div:before

I wrote some code to create a layover with some text. Now I have two problems:

1) I want to center the text.
2) I want to make the layover to be a link.

As I am a CSS newbie, I hope you can give me any advice!

Best regards!



.hover_div {
position:relative;
width:200px;
height:200px;
}
.hover_div img {
width:100%;
vertical-align:top;
}
.hover_div:after {
content: "";
position: absolute;
width:100%; height: 100%;
top: 0; left: 0;
background:rgba(0,0,0,0.6);
opacity:0;
transition: all 0.5s;
-webkit-transition: all 0.5s;
}

.hover_div:before {
content: attr(data-content);
color:#fff;
position:absolute;
opacity:0;
transition: all 0.5s;
-webkit-transition: all 0.5s;
z-index: 1;
}
.hover_div:hover:after {
opacity:1;
}

.hover_div:hover:before {
opacity:1;
}

<div data-content="Elektro" class="hover_div">
<img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>




Answer

I've updated your code in the following JSFiddle: https://jsfiddle.net/rvxo7fn5/

I've added the following lines to the :before:

text-align:center;
width: 100%;
margin-top:50%;
transform: translateY(-50%);

Basically, text-align: center; of course centers the text horizontally. However, an absolute positioned div has no width, which is why I added the width: 100%. Next you need to center it vertically. The margin-top: 50%; moves the div 50% of the height of the parent div. transform: translateY(-50%) moves the div back 50% of the height of the div itself. This aligns it in the center of the parent. (50% of parent height - 50% height of child div).

You also mentioned wanting it to be a link. This can be achieved by simply replacing the <div> with a <a> and adding display: block; to your .hover_div class. This gives it the properties a div would also have.

Hope that helps!