3

I am trying to overlay text with a white translucent background on an image when people mouse over that image. I found answers containing original type of the following code on here. Now I want to vertically align text to the middle of the image.

Is it possible?

HTML:

<div class="image">
    <img src="http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg" alt="" />
</div>

CSS:

.image {
    position:relative;
    width:400px;
    height:400px;
}
.image img {
    width:100%;
    vertical-align:top;
}
.image:after {
    content: 'Hello';
    color: #000000;
    vertical-align: middle;
    text-align: center;
    position: absolute;
    width:100%; 
    height:100%;
    top:0; 
    left:0;
    background: rgba(255,255,255,0.7);
    opacity:0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
}
.image:hover:after {
    opacity:1;
}
TylerH
  • 19,065
  • 49
  • 65
  • 86
YEON.JAE
  • 43
  • 2
  • I used display property already, it didn't work – YEON.JAE Dec 22 '14 at 18:29
  • 1
    @YEON.JAE For future reference, do note that sometimes, when someone marks a question as a duplicate, there might be a useful answer *other than* the accepted answer on the linked question. In this case, the second answer in Biscuit's link uses the line height example :-) – TylerH Dec 22 '14 at 19:01

2 Answers2

1

If the height of the image (or container) you are using is fixed, as in your example, then you can use a line-height method, as follows for the code in your example:

.image:after {
    line-height: 400px;
}

Add that line to the .image:after selector, and it will achieve what you want.

JSFiddle Example

TylerH
  • 19,065
  • 49
  • 65
  • 86
  • Thank you. May I ask one more? If the height is not fixed, is it impossible then? – YEON.JAE Dec 22 '14 at 18:43
  • @YEON.JAE I don't know – TylerH Dec 22 '14 at 18:43
  • This does not work when we have a longer text, which may spill over to the next line. – Vipin Kp Apr 11 '20 at 06:39
  • @VipinKp That's true, but it also wasn't what OP asked for, so there's no reason to downvote for a solution that meets the criteria specified. More importantly, you shouldn't be paying attention to this Q&A beyond clicking through to the duplicate target at the top which has more canonical solutions. – TylerH Apr 12 '20 at 16:23
0

This is more sure and structured to clean spaces.

.image:after {
    line-height: 400px;
    margin: 0;
    padding: 0;
}
supportsp
  • 63
  • 2
  • 11