























为代码块设置固定高度并允许滚动
在主题自定义器或子主题的style.css中添加:
/* 为所有代码块设置固定高度 */
.wp-block-code pre,
pre.wp-block-code {
max-height: 300px; /* 设置最大高度 */
overflow-y: auto; /* 垂直方向超出时显示滚动条 */
overflow-x: auto; /* 水平方向超出时显示滚动条 */
padding: 15px;
background-color: #f5f5f5;
border-radius: 5px;
line-height: 1.5;
}
/* 或者只为特定的代码块设置 */
.code-scrollable pre {
max-height: 300px;
overflow-y: auto;
overflow-x: auto;
}
/* 优化滚动条样式(可选) */
.wp-block-code pre::-webkit-scrollbar {
width: 8px;
height: 8px;
}
.wp-block-code pre::-webkit-scrollbar-thumb {
background: #ccc;
border-radius: 4px;
}
.wp-block-code pre::-webkit-scrollbar-track {
background: #f1f1f1;
}
/* 小代码块 */
.small-code pre {
max-height: 200px;
overflow: auto;
}
/* 中代码块 */
.medium-code pre {
max-height: 400px;
overflow: auto;
}
/* 大代码块 */
.large-code pre {
max-height: 600px;
overflow: auto;
}
安装后直接在插件中添加CSS代码。
创建新的代码片段,选择只在前端加载:
add_action('wp_head', function() {
echo '<style>
.wp-block-code pre {
max-height: 300px;
overflow: auto;
padding: 15px;
}
</style>';
});
// 添加自定义CSS
function custom_code_block_styles() {
echo '<style>
/* 固定高度并允许滚动 */
.wp-block-code pre {
max-height: 300px;
overflow-y: auto;
overflow-x: auto;
padding: 1em;
background: #f5f5f5;
border: 1px solid #ddd;
border-radius: 4px;
}
/* 调整行号和代码显示 */
.wp-block-code code {
display: block;
white-space: pre;
}
</style>';
}
add_action('wp_head', 'custom_code_block_styles');
/* 通过页面ID或类名指定 */
.page-id-123 .wp-block-code pre,
.post-id-456 .wp-block-code pre {
max-height: 400px;
overflow: auto;
}
/* 或使用文章类型 */
.single-post .wp-block-code pre {
max-height: 350px;
overflow: auto;
}
.wp-block-code pre {
max-height: 300px;
overflow: auto;
}
@media (max-width: 768px) {
.wp-block-code pre {
max-height: 250px;
}
}
@media (max-width: 480px) {
.wp-block-code pre {
max-height: 200px;
}
}
.wp-block-code {
position: relative;
}
.wp-block-code::after {
content: "↕ 可滚动";
position: absolute;
top: 5px;
right: 10px;
font-size: 12px;
color: #999;
opacity: 0.7;
}.wp-block-code {
position: relative;
}
.wp-block-code::after {
content: "↕ 可滚动";
position: absolute;
top: 5px;
right: 10px;
font-size: 12px;
color: #999;
opacity: 0.7;
}
/* 针对SyntaxHighlighter */
.syntaxhighlighter {
max-height: 300px !important;
overflow-y: auto !important;
}
/* 针对Prism.js */
pre[class*="language-"] {
max-height: 300px;
overflow: auto;
}
一般来说方法一(自定义CSS)是最简单直接的解决方案。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。