如何为所有slug含camera-crews的页面批量应用CSS规则?
Hey Spencer, great question! Here are a few reliable ways to target these pages—pick the one that fits your website's setup best:
1. 模板/服务器端添加专属类(推荐方案)
This is my go-to method because it's clean, performant, and avoids any front-end hacks. The idea is to add a custom CSS class to your page's <body> tag only when the slug contains camera-crews, then target that class in your CSS.
示例:WordPress站点
把这段代码加到主题的header.php文件里(建议用子主题修改,避免主题更新时丢失更改):
<body <?php body_class( str_contains( get_post_field( 'post_name', get_post() ), 'camera-crews' ) ? 'camera-crew-page' : '' ); ?>>
之后在你的CSS文件里写规则:
/* 给所有camera crew页面设置全局样式 */ .camera-crew-page { background-color: #f5f5f5; } /* 或者针对特定元素设置样式 */ .camera-crew-page .hero-banner { height: 400px; }
示例:静态站点生成器(Jekyll/Eleventy/Gatsby)
如果你用Liquid、Nunjucks这类模板语言的静态站点工具,给<body>标签加条件类即可:
<!-- Jekyll示例 --> <body class="{% if page.url contains 'camera-crews' %}camera-crew-page{% endif %}">
CSS规则和上面一致即可。
2. 纯前端JS动态添加类(应急方案)
如果你无法修改站点模板(比如用托管式CMS没有模板权限),可以用JavaScript检测当前slug并动态添加类:
// 确保DOM加载完成后执行 document.addEventListener('DOMContentLoaded', () => { const currentSlug = window.location.pathname.split('/').filter(Boolean).pop(); if (currentSlug.includes('camera-crews')) { document.body.classList.add('camera-crew-page'); } });
之后同样使用.camera-crew-page的CSS规则。
3. URL属性选择器(不推荐,仅应急)
你可以直接通过URL用CSS属性选择器定位页面,但这种方法很脆弱——如果URL里的参数或子目录包含camera-crews,可能会误判目标页面:
/* 定位所有URL包含"camera-crews"的页面 */ html:where([data-url*="camera-crews"]) { /* 你的样式规则 */ }
注意:你需要先给<html>或<body>标签添加data-url属性(可以用方法2里的JS来实现)。
Hope one of these works for you! Let me know if you need help adapting it to your specific platform.
内容的提问来源于stack exchange,提问作者John

