Set line-height as a percentage relative to the parent element

I have a responsive element where it's width and height will both scale. Inside this I have some text which I want to center vertically.

How can I set the text's line-height to be the same as it's parent if I don't know the parent's height?

line-height: 100% is relative to the font's regular height so this doesn't help...


Solution 1:

Here's another way to center an element vertically. I came across this technique some time ago. Basically it uses a pseudo element and vertical-align: middle.

.block::before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can
   also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

Solution 2:

Since it's 2019 already, you could also use flexbox to achieve this :)

To do so, add the following classes to the parent element:

display: flex;
flex-direction: column;
justify-content: center;

See this Fiddle

Solution 3:

I'd try putting the text inside another element, of which you know (or set) the size. Then setting relative positioning to it, top, left 50% and negative left and right margins.

See this Fiddle

The only problem is that this relies on a known/fixed textblock. If the text is variable, I'm afraid you will have to resort to using Javascript..