R McK R McK - 17 days ago 5
CSS Question

Vertically align content & 2 lines of text

I have 5 boxes that contain text that changes on hover.

However if the 'content' of a box has more than one line, it pushes the other boxes down slightly.

Also, how do I center the content vertically? Line-height does the job-ish but some of the text is more than one line. Also vertical-align seems to apply to the whole div rather than just the text in content



.image {
width: 204px;
height: 204px;
background-image: url('imglink');
display: inline-block;
background-repeat: no-repeat;
margin-left: 22px;
margin-right: 22px;
font-family: "Verdana", Geneva, sans-serif;
color: white;
font-size: 11pt;
}

.image:hover{
cursor: pointer;

}

.image:after {
width: 204px;
height: 204px;
display: inline-block;
background-repeat: no-repeat;
/* Content is inserted */
content: 'This text is already there';

}

.image:hover:after{
background-image: url('/imglink');
cursor: pointer;
content: 'This text will appear on hover';

}

<div class="image">
</div>





Here's the CSS, identical for all 5 boxes except different content.
Having massive difficulties sorting this as searching for "content" on Google doesn't really come up with the CSS "content"

Here's a fiddle: https://jsfiddle.net/su8bytdc/7/

Answer

Simply add display: flex and align-items: center to your :after selector and position: relative to your div .image.

To align the content horizontally just add text-align: center to .image and justify-content: center to the :after element

So your updated code would look something like this

.image {
  position: relative;
  width: 204px;
  height: 204px;
  display: inline-block;
  background-color: red;
  margin-left: 22px;
  display: inline-block;
  margin-right: 22px;
  font-size: 11pt;
  cursor: pointer;
  text-align: center;
}
.image:after {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  /* Content is inserted */
  content: 'This text is already there Even multiple lines';
}
.image:hover:after {
  text-align: center;
  content: 'This text will appear on hover';
}
<div class="image">
</div>
<div class="image">
</div>
<div class="image">
</div>
<div class="image">
</div>
<div class="image">
</div>

Comments