为何设置Span宽度无法脱离父Div的尺寸限制?
解决Flex容器中子元素宽度被自动均分的问题
问题原因
父元素.field设置了display: flex,flex子元素默认的flex-shrink: 1会让它们自动收缩以适应容器宽度,再加上justify-content: space-between的布局规则,导致两个span被均分了父容器的宽度,忽略了你设置的自定义宽度。
解决方案
给两个span(.scrollable_section)添加flex-shrink: 0属性,禁止它们自动收缩,同时调整父容器的布局方式,避免不必要的间距:
修改核心CSS代码
.scrollable_section { width: 125px; overflow-x: auto; overflow-y: hidden; white-space: nowrap; scrollbar-width: none; border: #000 1px solid; flex-shrink: 0; /* 新增:禁止子元素收缩 */ } .field { display: flex; /* 移除justify-content: space-between,避免自动分配间距 */ align-items: center; width: 150px; height: 16px; background-color: red; overflow: hidden; white-space: nowrap; transition: all 1s; }
完整代码示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> html, body { height: 100%; } body { display: flex; justify-content: center; align-items: center; background: #333; font-family: 'Lato', sans-serif; gap: 10px; /* 优化按钮与容器的间距 */ } .scrollable_section { width: 125px; overflow-x: auto; overflow-y: hidden; white-space: nowrap; scrollbar-width: none; border: #000 1px solid; flex-shrink: 0; /* 禁止收缩,保持自定义宽度 */ } .scrollable_section::-webkit-scrollbar { width: 0; height: 0; } .field { display: flex; align-items: center; width: 150px; height: 16px; background-color: red; overflow: hidden; white-space: nowrap; transition: all 1s; } .verse-one { color: white; opacity: 1; transform: translateX(10px); transition: opacity 0.5s, transform 0.5s 0.5s; } .verse-two { color: #000; opacity: 0; transform: translateX(200px); transition: opacity 0.5s, transform 0.5s 0.5s; } .next-verse { background-color: rgb(255, 255, 255); } .next-verse .verse-one { opacity: 0; transform: translateX(-200px); } .next-verse .verse-two { opacity: 1; transform: translateX(-65px); } </style> </head> <body> <button onclick="toggleTransition()">Toggle Transition</button> <div class="field" id="example"> <span class="verse-one scrollable_section"> I am the very model of a modern major general. Ive information vegetable animal and mineral. I know the kings of england and quote the fights historical from marathon to waterloo in order categorical. </span> <span class="verse-two scrollable_section"> I am very well acquainted too with matters mathematical. I understand equations both the simple and quadratical. About binomial theorem I am teeming with a lot of news. With many cheerful facts about the square of the hypotenuse. </span> </div> <script> function toggleTransition() { var example = document.getElementById('example'); example.classList.toggle('next-verse'); } </script> </body> </html>
关键说明
flex-shrink: 0:强制子元素保持设置的宽度,不会被flex容器压缩。- 移除
justify-content: space-between:该属性会让flex子元素在容器内均匀分布,导致宽度被调整,去掉后子元素将按自身宽度排列。
内容的提问来源于stack exchange,提问作者JSArrakis
相关产品推荐
相关产品推荐

