Reputation: 8150
Consider an inline-block CSS element which can contain text, and which has some nice padding.
Depending on whether or not there's any text in the inline-block, the height of the element will vary:
.text-holder {
display: inline-block;
color: #ffffff;
padding: 10px;
vertical-align: top;
}
.text-holder.black { background-color: #000000; }
.text-holder.grey { background-color: #606060; }
<div class='text-holder black'>I HAVE TEXT</div>
<div class='text-holder grey'></div>
How can I ensure that the height of such elements is the same, whether or not there is any text inside the element, and regardless of the font-size?
At first I considered min-height
, but I don't believe that will work for variable font sizes.
Upvotes: 3
Views: 619
Reputation: 272965
Use a zero space character when empty:
.text-holder {
display: inline-block;
color: #ffffff;
padding: 10px;
vertical-align: top;
}
.text-holder.black { background-color: #000000; }
.text-holder.grey { background-color: #606060; }
.text-holder:empty::before {
content:"\200B";
}
<div class='text-holder black'>I HAVE TEXT</div>
<div class='text-holder grey'></div>
You can also keep it for all the element since it has 0 width:
.text-holder {
display: inline-block;
color: #ffffff;
padding: 10px;
vertical-align: top;
}
.text-holder.black { background-color: #000000; }
.text-holder.grey { background-color: #606060; }
.text-holder::before {
content:"\200B";
}
<div class='text-holder black'>I HAVE TEXT</div>
<div class='text-holder grey'></div>
Simply pay attention if have leading spaces:
.text-holder {
display: inline-block;
color: #ffffff;
padding: 10px;
vertical-align: top;
}
.text-holder.black { background-color: #000000; }
.text-holder.grey { background-color: #606060; }
.text-holder::before {
content:"\200B";
}
<div class='text-holder black'>I HAVE TEXT</div><br>
<div class='text-holder black'> I HAVE TEXT</div>
<div class='text-holder grey'></div>
Upvotes: 5
Reputation: 10021
The only way I can think of this working out for you is to use flexbox. See the code below. Basically, have a parent set as display: flex;
and that should keep all the heights on each line the same. So if line 2 has only small font sizes then that one line will all be equal heights, but the heights will all be smaller than line 1 for example
.parent {
display: flex;
flex-wrap: wrap;
}
.child {
padding: 10px;
border: 1px dashed #ddd;
display: flex;
align-items: center;
}
.lg {
font-size: 30px;
}
.md {
font-size: 20px;
}
.sm {
font-size: 14px;
}
<div class='parent'>
<span class='child lg'>some text</span>
<span class='child sm'>text more text</span>
<span class='child md'>child asdf</span>
<span class='child lg'>asl;fkj s</span>
<span class='child lg'>asdf</span>
<span class='child md'>asdf 1</span>
<span class='child sm'>alsdfj </span>
<span class='child lg'>asldfkj</span>
<span class='child sm'>asldfkj</span>
</div>
Upvotes: 0