My website features a sidebar menu that is resizable and has a collapse animation transition. Some of the text in this sidebar needs to be centered, but I've run into an issue - when using text-align: center;
to format the text, it shifts around as you resize its container div due to the changing center point.
To address this problem, I resorted to setting white-space: nowrap;
and manually adjusting the left padding to center the text. While this solution works well, the challenge arises with dynamically generated text that also requires centering. This means having to calculate the length of the text dynamically and adjust the padding accordingly, which doesn't seem like the right approach.
Is there a way to keep text centered in a div without shifting when the div is resized? It doesn't necessarily have to involve the use of the nowrap style.
You can view an illustration of the issue on jsfiddle here: https://jsfiddle.net/singerbradley/dvmauj3f/28/#&togetherjs=nvnJwReUA7
EDIT:
Let me clarify my goal - I want the text in the resizing div to remain centered even as the div is adjusted in width. Additionally, I prefer the text to appear cut off rather than wrap to the next line when the container shrinks. The desired outcome is demonstrated in the lower box, where the text remains stationary despite the container resizing (overflow: hidden;
and white-space: nowrap;
are used).
.enhance {
border-color: red;
border-style: solid;
margin-top: 10px;
margin-bottom: 10px;
padding: 20px 0;
width: 300px;
overflow: hidden;
transition: all .5s linear;
}
#wrap {
text-align: center;
}
#nowrap {
white-space: nowrap;
text-align: center;
}
#wrap:hover {
width: 50px;
}
#nowrap:hover {
width: 50px;
}
<p style="width:500px;">
Hover over each box to see it in motion. The centered, line wrap text shifts with div resize.
</p>
<div id="wrap" class="enhance">This text has line wraps.</div>
<div id="nowrap" class="enhance">This text has no line wraps.</div>