Div宽度超出100%时CSS margin-right失效,容器margin设置异常求助
解决宽div外层容器右侧margin不生效的问题
我帮你分析下这个问题:你遇到的情况是因为外层容器默认是块级元素,宽度固定为父容器(body)的宽度。当内层的flex内容超长时,内层div会超出外层容器的范围,页面横向滚动后,外层容器的右侧margin被挤到了视口外面,看起来像是没生效;而内容较短时,内层div没超出外层容器,所以左右margin都能正常显示。
这里给你一个可行的解决方案,关键改动如下:
- 把外层容器设为
display: inline-block,让它自适应内层内容的宽度,同时保留上下左右的margin - 调整内层div的最小宽度为
calc(100vw - 100px),确保内容较短时,内层div能占满去掉外层左右margin后的视口宽度(100vw是视口宽度,减去2*50px的margin) - 给内层flex容器所在的div添加
overflow-x: auto,内容超长时会出现横向滚动条,方便查看全部内容 - 去掉内层div的
display: inline-block,改用block避免行内布局的额外影响
修改后的完整代码:
<html> <body> <div style="margin: 50px; display: inline-block;"> <div style="white-space: nowrap; font-size: 12px;font-weight: 600;text-transform: uppercase;color: #7a7a7a;background: #dedede;border-radius: 3px 3px 0px 0px;font-family:;display: block;min-width: calc(100vw - 100px);overflow-x: auto;"> <div style="display: flex; flex-wrap: nowrap"> <div>oneon e saf </div> <div> </div> <div style="width: 10px; margin: 0 100px; white-space: normal;">This is a div heheheh</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> <div>oneon e saf </div> <div> </div> <div>This is a div</div> </div> </div> <div style="background-color: gray; margin-top: 10px;">This is another div</div> </div> </body> </html>
这样修改后,不管内容长短,外层容器的左右margin都会正常显示,长内容也能在带margin的容器里通过横向滚动查看全部内容。
内容的提问来源于stack exchange,提问作者Liga
相关产品推荐
相关产品推荐

