You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Pre标签导致卡片超出容器,实现Pre标签内容内部滚动?

解决pre标签导致卡片超出容器的横向滚动问题

我来帮你搞定这个问题!你现在遇到的情况是pre标签里的长内容把卡片撑大,导致整个页面出现横向滚动条——这确实很烦人。要实现像Stack Overflow那样只在代码块内部显示滚动条的效果,只需要调整几处CSS就行:

修改后的CSS代码

.main { 
    width: 100%; 
    background-color: green; 
    display: flex; 
    flex-direction: row; 
    justify-content: stretch; 
    align-items: flex-start; 
    padding: 20px; 
    box-sizing: border-box; 
}
.menu { 
    width: 200px; 
    height: 300px; 
    background-color: red; 
    flex-grow: 0; 
    flex-shrink: 0; 
}
.card-container { 
    box-sizing: border-box; 
    background-color: blue; 
    height: 500px; 
    display: flex; 
    flex: 1; 
    flex-direction: column; 
    align-items: stretch; 
    justify-content: flex-start; 
}
.card { 
    position: relative; 
    flex-grow: 1; 
    flex-shrink: 1; 
    flex-basis: 0; 
    margin: 20px; 
    background-color: yellow; 
    height: 300px;
    /* 关键:防止内部元素撑开卡片宽度 */
    overflow-x: hidden;
}
pre { 
    background-color: black; 
    color: white; 
    /* 让代码块宽度完全适配卡片 */
    width: 100%;
    box-sizing: border-box;
    /* 仅内容超出时显示横向滚动条 */
    overflow-x: auto;
    /* 保留代码格式,不自动换行 */
    white-space: pre;
    /* 可选:加内边距让代码更美观 */
    padding: 1em;
}

关键修改说明

  • 给.card添加overflow-x: hidden:这能确保pre之类的内部元素不会把卡片的宽度撑到超出容器范围,从根源上避免页面出现横向滚动。
  • 调整pre的样式:
    • width: 100% + box-sizing: border-box:让代码块的宽度严格贴合卡片的可用空间,即使你给pre加了内边距也不会超出。
    • overflow-x: auto:只有当代码内容长度超过代码块宽度时,才会显示横向滚动条,比固定的scroll更友好(不会一直显示空的滚动条)。
    • white-space: pre:保留代码里的换行和空格格式,同时禁止自动换行——这样长代码才会触发横向滚动,而不是自动折行。

小提示

你HTML里的pre标签内部文本有多余的缩进,这会导致代码块前面出现一大段空白,建议把pre里的内容对齐到左边缘,比如:

<pre>Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa placeat quia cum, corporis amet quas repellat, nostrum inventore numquam accusamus possimus minima maxime error iusto obcaecati consequuntur fugiat magnam. Temporibus?</pre>

这样调整后,你的代码块就会和Stack Overflow的一样,只在内部滚动,不会影响整个页面啦!

内容的提问来源于stack exchange,提问作者Meet Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 18:22:48