导航栏初始适配屏幕宽度,滚动时无法匹配动态表格宽度求助
解决导航栏与动态表格宽度不匹配的问题
问题根源:你给.topnav设了width:100vw,这个值只对应浏览器视口的宽度。当表格新增列后宽度超出视口,页面会出现横向滚动条,但导航栏不会跟着页面整体宽度扩展,所以滚动后导航栏就比表格窄了。
直接按下面的步骤修改代码:
1. 调整导航栏和body的CSS样式
把.topnav里的width:100vw删掉,改成width:100%;同时给body添加min-width: fit-content,让body的宽度自动适配表格的最大宽度:
body { font-family: Arial, Helvetica, sans-serif; font-size: 16px; zoom: 175%; min-width: fit-content; /* 新增这行 */ } .topnav { overflow: hidden; background-color: #333; display: flex; /* 删掉width:100vw */ position: sticky; top: 0; width: 100%; /* 改成这个 */ }
2. 优化表格容器(可选但推荐)
取消table-container的注释,给它加上overflow-x: auto,这样表格超出时会在容器内横向滚动,体验更好:
.table-container { width: 100%; overflow-x: auto; /* 新增这行 */ }
修改后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Flask Web Form</title> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}"> <style> body { font-family: Arial, Helvetica, sans-serif; font-size: 16px; zoom: 175%; min-width: fit-content; } .topnav { overflow: hidden; background-color: #333; display: flex; position: sticky; top: 0; width: 100%; } .topnav a { float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } .topnav a:hover { background-color: #ddd; color: black; } .topnav a.active { background-color: #AAC939; color: white; } .form-container { display: flex; flex-direction: column; align-items: center; } label { margin-right: 5px; } .table-container { width: 100%; overflow-x: auto; } </style> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <!-- BODY --> <body style="background-color: white;"> <div class="topnav"> <a href="{{ url_for('index') }}">Section 1</a> <a class="active" href="{{ url_for('show_table') }}">Section 2</a> <a href="{{ url_for('admin') }}">Section 3</a> </div> <header> <title>Form Data</title> </header> <div class="table-container"> <table border="1" class="table table-striped" style="white-space:nowrap"> <thead> <tr> {% for column_name in column_names %} <th>{{ column_name|replace('_', ' ') }}</th> {% endfor %} </tr> </thead> <tbody> {% for row in rows %} <tr> {% for item in row %} <td>{{ item|replace('_', ' ') }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> </body> </html>
额外提醒:你页面里同时引入了Bootstrap 3和Bootstrap 4,这可能导致样式冲突,建议只保留一个版本。
内容的提问来源于stack exchange,提问作者cheznead
相关产品推荐
相关产品推荐

