Set line-height as a percentage relative to the parent element
CssCss Problem Overview
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...
Css Solutions
Solution 1 - Css
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 - Css
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 - Css
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.
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..
Solution 4 - Css
Regarding hyperlinks:
I was having this problem regarding links in main menu. And since it was <a>
in <li>
tags I needed some surface for the links to be clickable/touchable(see touch target size).
So what I did was for the <ul>
I set a fixed height(through it's parent in this case), the <li>
-s are a percentage of it and the <a>
-s have a min-height and line-height properties set to them and it's easy from there to set the top. The code:
.menu-header-main-container{
position: fixed;
top: 0;
bottom: 160px;
}
.menu-header-main-container ul.menu {
height: 100%; }
.menu-header-main-container ul.menu li {
height: 33.33%;
max-height: 110px; }
.menu-header-main-container ul.menu li a {
line-height: 40px;
min-height: 40px;
top: calc(50% - 20px);
position: relative; } }
Solution 5 - Css
You cannot set the line-height to 100% of the parent element's height with only CSS. Rather, you can use CSS to center an element vertically.
.parent {
height:150px;
position:relative;
border:1px solid #FDD;
}
.position-center {
position:absolute;
top:50%;
transform:translateY(-50%);
}
<div class="parent">
<span class="position-center">I am vertically centered element</span>
</div>