如何实现等宽并排、带横向滚动的代码框(保留空格不换行)
Fixing Equal-Width Side-by-Side Code Boxes with
white-space: pre Got it, let's sort out this issue! The problem you're hitting comes down to how flexbox handles the minimum width of its child elements. By default, flex items won't shrink smaller than their content's intrinsic width—so when you use white-space: pre, that long unbroken line in your XML content is forcing its column to stretch wider than the other one.
Here's the corrected solution, with breakdowns of the key fixes:
Modified Full Code
<div class="columns"> <div class="column"> <div id="xml" class="code"> xml </div> </div> <div class="column"> <div id="json" class="code"> json </div> </div> </div> <style> .columns { display: flex; flex-direction: row; width: 100%; gap: 1rem; /* Optional: adds space between columns for better readability */ } .column { flex: 1; min-width: 0; /* Critical fix: lets flex items shrink below content width */ } .code { overflow: auto; white-space: pre; font-family: monospace; padding: 1rem; /* Optional: adds padding inside code boxes */ border: 1px solid #ddd; /* Optional: adds border for clarity */ } </style> <script> window.document.querySelector("#xml").textContent = `<note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>You should probably need to scroll to see this long line!</body> </note>`; // Add sample JSON content to test the second column window.document.querySelector("#json").textContent = `{ "note": { "to": "Tove", "from": "Jani", "heading": "Reminder", "body": "You should probably need to scroll to see this long line!" } }`; </script>
Key Fixes Explained:
- Swapped
<span>for<div>in.code: Span elements are inline by default, which can cause wonky layout behavior with block-style code content. Using a div ensures the code box acts as a proper block element. - Added
min-width: 0to.column: This is the make-or-break change. Flex items have a defaultmin-width: auto, which stops them from shrinking smaller than their content's width. Settingmin-width: 0overrides this rule, forcing each column to take an equal share of the container's width—even if their content is wider than the column. - Optional polish: The
gap,padding, andborderare just to make the code boxes look cleaner—feel free to tweak or remove them based on your design needs.
With these adjustments, your code boxes will stay perfectly equal-width, preserve all whitespace and line breaks, and show scrollbars for any content that overflows the column width.
内容的提问来源于stack exchange,提问作者user1283776
相关产品推荐
相关产品推荐

