Text Centered on a Line
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. However, unfortunately, the answer pointed to for as the solution for the duplicate does not dynamically grow and shrink the colored box around the text:
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:
Instead of a percentage padding to create the dynamically growing/shrinking colored box around the text, I use
flex: 1; for the
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-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
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.