如何让JSP页面中的div元素横向并排显示?
Hey there! Let's get those elements lined up horizontally instead of stacking. Since you're new to CSS, I'll break this down step by step so it's easy to follow. Looking at your code, there are two key tweaks we need to make—one to the HTML structure and one to the CSS—to fix the layout.
1. Fix the Column Width on Your Second Table Container
In your second <div class="panel-body">, the table container uses col-lg-12 which makes it take up the entire row, pushing it below the input and button. Let's change that to match the first div's table container class so it shares the row space properly:
<!-- 修改前 --> <div class="col-lg-12 col-xs-12" id="jobSuccessionListDiv_1"> <!-- 修改后 --> <div class="form-group col-lg-6 col-xs-12 float2" id="jobSuccessionListDiv_1">
2. Use Flexbox to Force Horizontal Layout
Bootstrap's grid works, but adding a flex layout to the panel-body will give us better control over keeping elements side-by-side. Let's add a custom CSS class and update the HTML:
First, add this CSS to your stylesheet (or a <style> tag in your JSP):
/* 让panel-body的子元素横向排列,小屏幕自动换行保证响应式 */ .flex-horizontal { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 1.5rem; /* 给元素之间留空隙,避免拥挤 */ } /* 禁用浮动,flex布局不需要它 */ .flex-horizontal .float2 { float: none !important; } /* 确保每个区域在flex布局下合理分配空间,小屏幕设置最小宽度避免元素过窄 */ .flex-horizontal .col-lg-3, .flex-horizontal .col-lg-2, .flex-horizontal .col-lg-6 { flex: 1; min-width: 220px; } /* 让按钮区域垂直居中,和输入框对齐更美观 */ .flex-horizontal .col-lg-2 { align-self: center; }
Then update both of your panel-body tags to include the new class:
<!-- 第一个div的panel-body --> <div class="panel-body flex-horizontal"> <!-- 第二个div的panel-body --> <div class="panel-body flex-horizontal">
Why This Works
- Flexbox is the modern, reliable way to create horizontal layouts—it handles alignment and spacing way better than old float hacks, especially for dynamic content.
- Changing the second table's column class stops it from taking the whole row, so it can sit next to the input and button.
flex-wrap: wrapensures that on small screens (like phones), the elements will stack vertically instead of overflowing, keeping your page user-friendly across devices.
Give these changes a try, and your inputs, buttons, and tables should all line up horizontally in each panel. Let me know if you run into any snags!
内容的提问来源于stack exchange,提问作者Travelling Salesman

