I'm attempting to vertically center text, which wraps to multiple lines, within a div, while not allowing that div to be re-sized based on the amount of text that it contains. Any text that does not fit within the specified height and width should be cut off (preferably with an ellipsis).
The text needs to be within a span
element layered within two div
s.
<div class="outer-div">
<div class="inner-div">
<span class="course-name">Text Here</span>
</div>
</div>
The issue I'm having is that in order to get the div to not re-size vertically to fit the text I have to set the display
to inline-block
. However once I do this, the text is no longer vertically centered, but is instead top aligned.
I have read through this post, and played around with its suggestions. However, although these methods (specifically the table display version) do allow for vertical alignment, I still cannot achieve simultaneous centering and fixed height.
Here is a demo of the scenario I'm describing, and below is the CSS from this demo that creates this problem.
Note how in the demo when you uncomment the line which sets display: inline-block
, the top div shrinks to the proper height (and exactly matches the size of the second div).
.outer-div, span {
width: 120px;
height: 45px;
}
.outer-div {
text-align: center;
display: table;
background-color: blue;
color: white;
}
.inner-div {
display: table-cell;
vertical-align: middle;
}
span {
font-weight: bold;
overflow: hidden;
text-overflow: ellipsis;
/* The line in question */
display: inline-block;
}
What is the best way to achieve vertical centering of multiple lines of text within a div
with a fixed height and width?
you need to make changes on two places.
instead of using
.outer-div, span {...}
use only
.outer-div {...}
and for the span, following rule will work
span {
font-weight: bold;
overflow: hidden;
text-overflow: ellipsis;
width: 120px;
display: inline-block;
max-height: 45px;
}
and you are done. here is your working fiddle