Text Centered on a Line - Stack Overflow Answer
There was a question on StackOverflow that was closed, so I could not answer it on StackOverflow directly. So, I am answering it here on my website. The question title was originally Horizontally align text with lines in the middle, now marked duplicate:
The person who asked the question wanted to proportionally grow and shrink a colored box around centered text on a line, but the text kept wrapping at the space between the two words. Unfortunately, the answer pointed to as the solution for the duplicate does not dynamically grow and shrink the colored box around the text:
Stack Overflow Duplicate Question
The answer given in the duplicate question did not address a dynamically growing/shrinking box around the text, only a static, unchanging one.
I achieved the desired effect, which does not break whether the viewport is very narrow, or vary wide, like the three answers given in the original question before it was closed. Here is the code:
CSS
HTML
Working Example
Just below, you will see the example embedded in this post. Resize the viewport and you will see the appropriate behavior:
Some Text
Click here to see it full width in a new tab.
Explanation
Instead of a percentage padding to create the dynamically growing/shrinking colored box around the text, I use flex: 1;
for the <span>
which holds the text, and a flex: 4;
for the lines. Each of these flex
lines in the CSS sets the flex-grow
to the indicated value for
the three items (two lines and a <span>
), also setting defaults for flex-shrink
and flex-basis
. Each line is then four times the width of the
<span>
as the container shrinks and grows, which roughly does what the OP did with the padding percentages.
I set the min-width
to max-content
for the <span>
, which stops it from shrinking to cause a wrap, then hard-code a padding of 8px
to make sure
there is a minimum amount of colored box on either side of the <span>
if the width of the container shrinks so small that there would be nothing
on either side.