Take a look at this straightforward solution without any extra markup:
.vertically-centered {
border: 1px solid red;
height: 6rem;
overflow: hidden;
font-weight: bold;
font-size: 2.5rem;
text-overflow: ellipsis;
width: 300px;
line-height: 1.2;
display: flex; /* allows centering for modern non-webkit browsers */
flex-direction: column;
justify-content: space-around; /* centers for modern non-webkit browsers */
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
-webkit-box-pack: center; /* automatic centering in -webkit-box! */
}
<div class="vertically-centered">vertically centered with</div>
<div class="vertically-centered">vertically centered with hello</div>
<div class="vertically-centered">one line</div>
You can test out this solution by viewing the updated example on
CodePen.
How it functions: Your original code already utilizes Flexbox layout for WebKit-based browsers (despite being outdated 2009 syntax), yet unfortunately, -webkit-line-clamp
no longer works with newer implementations. Flexbox has its own mechanism for vertical centering. To achieve the desired behavior in WebKit-based browsers, simply remove the :after
pseudo-element and replace it with the following line of code in .vertically-centered
:
-webkit-box-pack: center;
For other modern browsers like Firefox 22+ and IE11+, you can achieve the same layout (excluding the ellipsis) using the new version of Flexbox:
display: flex;
flex-direction: column;
justify-content: space-around;
This should be placed above display: -webkit-box
in the code so that WebKit browsers can still apply -webkit-line-clamp
.
To make it compatible with IE10, add its prefixed version of Flexbox (2011 transitional syntax):
display: -ms-flexbox;
-ms-flex-direction: column;
-ms-flex-pack: center;
You can find the pen with IE10 support here: http://codepen.io/anon/pen/otHdm
The :after
method for vertical centering did not work in the first 'cell' due to the following reason: for inline-level CSS boxes (like standard text, inline blocks, images, etc.), vertical-align
adjusts the baselines of all such boxes forming a line box. The height of the line box is calculated so that all inline-level boxes fit into it, making it impossible for the line box's height to be shorter than the tallest inline-level box within it. Therefore, your :after
inline block, which takes up 100% of the container height, becomes the tallest element in the last line of your block. Due to vertical-align: middle
, the baseline of the last line's text aligns with the vertical middle of the text and the tall inline-block. This scenario is fine when there is only one line (the usual case for centering) or when the last line is hidden with overflow
, but it causes issues when visible).