如何使菜单元素在浏览器窗口缩放时始终保持在同一行?
Hey there! Let's get that menu sorted so your elements stay in a single row no matter how the browser window is resized.
The Root of the Problem
Your current setup uses float: left for .tripleDot elements, which works fine until the container (.mainMenu) doesn't have enough horizontal space. Floated elements will wrap onto new lines when they can't fit, causing that messy offset you're seeing.
Solution 1: Use Flexbox (Recommended)
Flexbox is made for exactly this kind of one-dimensional layout. It'll keep your items aligned in a row without wrapping, and gives you better control over spacing and alignment. Here's how to update your CSS:
.mainMenu { width: 100%; position: absolute; top: 90px; z-index: 100; /* Add Flexbox properties */ display: flex; align-items: center; /* Vertically centers items (optional but nice) */ flex-wrap: nowrap; /* Forces all items to stay in one row */ overflow-x: auto; /* Adds horizontal scroll if items overflow (optional) */ } .mainMenu .tripleDot { /* Remove float: left — Flexbox handles positioning now */ width: 90px; font-family: Georgia, serif; font-size: 40px; font-style: italic; font-weight: bold; margin: 5px; line-height: 40px; text-align: center; }
Why This Works:
display: flexturns.mainMenuinto a flex container, making its children flex items.flex-wrap: nowrapensures items never wrap to a new line, even if the container is too narrow.overflow-x: autoadds a horizontal scrollbar if the total width of items exceeds the container, so users can still access all elements.
Solution 2: Inline-Block + White-Space (For Older Browser Support)
If you need to support older browsers that don't handle Flexbox well, this approach uses inline-block elements and prevents wrapping with white-space: nowrap:
.mainMenu { width: 100%; position: absolute; top: 90px; z-index: 100; white-space: nowrap; /* Stops elements from wrapping */ overflow-x: auto; /* Optional scroll for overflow */ } .mainMenu .tripleDot { display: inline-block; /* Replaces float: left */ width: 90px; font-family: Georgia, serif; font-size: 40px; font-style: italic; font-weight: bold; margin: 5px; line-height: 40px; text-align: center; }
Quick Note on Absolute Positioning
Just make sure that the parent element of .mainMenu has position: relative set if you want .mainMenu to be positioned relative to it. If there's no parent with relative positioning, .mainMenu will be positioned relative to the entire document, which might be what you want—but it's good to double-check!
内容的提问来源于stack exchange,提问作者tolik

