Swagger UI 主题样式修改

改主色、换 logo、调默认展开、去掉顶部栏,以及自定义 CSS 的注入方式。

Intermediate
Key Points优先用官方配置项(docExpansion、deepLinking、tryItOutEnabled)解决行为问题,视觉再用自定义 CSS 覆盖。

先看配置项

OptionEffect
docExpansionnone / list / full — collapse tags by default
defaultModelsExpandDepth-1 hides the Models section
tryItOutEnabledEnable the try-it form on load
filterShow the search box
deepLinkingURLs reflect the current operation
persistAuthorizationKeep the token across reloads
JavaScript
SwaggerUIBundle({
  url: "./openapi.yaml",
  dom_id: "#swagger-ui",
  docExpansion: "list",
  defaultModelsExpandDepth: -1,
  tryItOutEnabled: true,
  filter: true,
  deepLinking: true,
  persistAuthorization: true,
});

覆盖样式

Swagger UI's class names are stable enough to override directly. Use !important sparingly or upgrades will fight you.

CSS
/* 主色 */
.swagger-ui .topbar { background-color: #0f172a; }
.swagger-ui .info .title { color: #0f172a; }
.swagger-ui .opblock.opblock-get { border-color: #2563eb; }
.swagger-ui .opblock.opblock-get .opblock-summary-method { background: #2563eb; }

/* 字体 */
.swagger-ui { font-family: "Inter", system-ui, sans-serif; }

/* 隐藏顶部栏 */
.swagger-ui .topbar { display: none; }
HTML
<link rel="stylesheet" href="./custom.css">

换 logo

CSS
.swagger-ui .topbar-wrapper .link svg { display: none; }
.swagger-ui .topbar-wrapper .link {
  background: url("./logo.svg") no-repeat center / contain;
  width: 140px; height: 36px;
}

深色模式

CSS
@media (prefers-color-scheme: dark) {
  body { background: #0b1220; }
  .swagger-ui { filter: invert(0.92) hue-rotate(180deg); }
  .swagger-ui img, .swagger-ui .microlight { filter: invert(1) hue-rotate(180deg); }
}
filter: invert() is the cheapest dark mode, but it flips images and code highlighting too — invert those back. For finer control, override the CSS variables instead.

Spring Boot 里注入

Java
@Configuration
public class SwaggerUiConfig {
    @Bean
    public SwaggerUiConfigProperties.Css css() {
        SwaggerUiConfigProperties.Css c = new SwaggerUiConfigProperties.Css();
        c.setUrl("/custom.css");
        return c;
    }
}

Friends & Partners