如何避免React结合MUI实现的字符拆分式动画单词在小屏幕上断行拆分?
Hey there! Let's fix that frustrating line-break issue with your animated "plants" word. The core problem here is that each character is wrapped in its own <span> element—so the browser treats them as separate inline items, and will wrap them individually when screen space runs out. Your earlier attempts with non-breaking spaces or word-break: keep-all didn't work because those tools target regular text content, not a set of separate inline elements.
Here are two straightforward, effective solutions:
Solution 1: Force No Wrapping on the Animated Container
Add white-space: nowrap to your AnimatedTypography styled component, along with display: inline-block to keep it aligned properly with the surrounding text. This tells the browser to keep all content inside the container on a single line.
const AnimatedTypography = styled(Typography)` & { position: relative; -webkit-box-reflect: below -20px linear-gradient(transparent, rgba(0, 0, 0, 0.2)); font-size: 60px; white-space: nowrap; /* Prevents any line breaks inside the container */ display: inline-block; /* Keeps the animated word aligned with adjacent text */ margin: 0 8px; /* Optional: Adds spacing around the word for better readability */ } & span { color: #fbbf2c; font-family: "Alfa Slab One", sans-serif; position: relative; display: inline-block; text-transform: uppercase; animation: waviy 1s infinite; animation-delay: calc(0.1s * var(--i)); } @keyframes waviy { 0%, 40%, 100% { transform: translateY(0); } 20% { transform: translateY(-20px); } } `;
Solution 2: Use an Inline Flex Container
If you want even more control over alignment, switch to display: inline-flex for the AnimatedTypography component. Flexbox will automatically keep all child <span> elements in a single line by default, and you can adjust vertical alignment easily.
const AnimatedTypography = styled(Typography)` & { position: relative; -webkit-box-reflect: below -20px linear-gradient(transparent, rgba(0, 0, 0, 0.2)); font-size: 60px; display: inline-flex; /* Inline flex container keeps all spans in one line */ align-items: center; /* Ensures consistent vertical alignment of characters */ white-space: nowrap; /* Extra layer of protection against wrapping */ margin: 0 8px; } & span { color: #fbbf2c; font-family: "Alfa Slab One", sans-serif; position: relative; display: inline-block; text-transform: uppercase; animation: waviy 1s infinite; animation-delay: calc(0.1s * var(--i)); } @keyframes waviy { 0%, 40%, 100% { transform: translateY(0); } 20% { transform: translateY(-20px); } } `;
Why This Works
Instead of trying to fix each individual character, we're controlling the container that holds all the animated spans. Both solutions ensure the entire "plants" word stays intact—when screen space is too small, the whole word will wrap to the next line as a single unit, rather than splitting mid-word.
内容的提问来源于stack exchange,提问作者user18943198

