如何实现flex容器元素向左溢出,加载时默认显示最右侧元素
实现Flex容器默认显示最右溢出元素的方案
核心修改逻辑如下:
- 修正基础布局的尺寸冲突,避免整体页面出现多余滚动条
- 给left容器配置正确的flex属性和滚动对齐逻辑
- 固定列的宽度不被flex布局自动压缩
修改后完整CSS代码
@import url("https://fonts.googleapis.com/css2?family=Heebo:wght@600&display=swap"); body { margin: 0; padding: 0; } .page-container { display: flex; flex-direction: column; height: 100vh; background-color: teal; align-items: stretch; } .banner { background-color: lightcyan; position: relative; width: 100%; height: 80px; flex-shrink: 0; } .banner-title { font-family: "Heebo"; font-weight: 600; font-size: 40px; padding: 10px; } .footer { width: 100%; background-color: thistle; height: 30px; flex-shrink: 0; } .body-container { background-color: lightcyan; flex: 1; display: flex; overflow: hidden; } .left-container { background-color: greenyellow; flex: 1; display: flex; flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; /* 核心属性:设置从右到左排版,默认滚动到最右侧 */ direction: rtl; } .right-container { background-color: tomato; width: 350px; flex-shrink: 0; height: 100%; } .column-container { background-color: red; width: 150px; margin: 5px; display: flex; flex-direction: column; flex-shrink: 0; /* 恢复列内内容的默认从左到右排版 */ direction: ltr; }
可选JS实现方案
如果不想修改direction属性,可以去掉CSS中direction相关配置,添加以下JS代码实现默认滚动到最右侧:
window.addEventListener('load', () => { const leftContainer = document.querySelector('.left-container') leftContainer.scrollLeft = leftContainer.scrollWidth - leftContainer.clientWidth })
原有HTML代码无需修改即可实现需求效果。
内容的提问来源于stack exchange,提问作者machine gurning
相关产品推荐
相关产品推荐

