| Note: When you edit this page, you agree to release your contribution under theCC0. SeePublic Domain Help Pages for more info. |
TemplateStyles enables the complex behavioral and aesthetic styling oftemplates through the use of referenced external CSS files that are wiki pages themselves.Notably, the ability to create/modify the CSS files is included in the default permissions forautoconfirmed users and so doesn't require involving someone withinterface administrator privileges.
Editors can add<templatestylessrc="[some page]" /> to a page and the contents of the referenced page will be parsed asCSS, sanitized and loaded on pages where the<templatestyles> tag is used (either directly, or transcluded by a template in use on the page).
[some page] must have thesanitized-css (Sanitized CSS)content model, which is the default for subpages in the Template namespace that end with.css.The recommended usage pattern is to store the styles forTemplate:Foo in a subpage of the template they're most impactful upon, such asTemplate:Foo/styles.css.If[some page] lacks a namespace prefix, it defaults to the Template namespace. Thus, for example,<templatestylessrc="Foo/styles.css"/> will loadTemplate:Foo/styles.css.
The<templatestyles> tag should be placed before the content that is styled, ideally at the top of the template or as close to there as possible, to avoid a potentialflash of unstyled content if the page becomes initially visible while still only partially rendered.
TemplateStyles allows editors to associate style rules to specific pages, provides the full power of CSS stylesheets while filtering dangerous constructs, and works with preview/debug tools (such asTemplateSandbox) as expected.
Lowering the access and maintainability barrier will hopefully result in more innovation in the way templates are visually designed, less maintenance overhead, and better adaptability to screen options (especially with mobile devices constitutingmore than half of Wikipedia pageviews even as of March 2016).
Traditionally, there were two ways to style templates (or any other content) on MediaWiki pages, with neither approach working especially well any of the following:
style="margin: 10px;")@media rules needed forresponsive design do not work so it's impossible to make templates that work well over a wide range of screen sizes. Furthermore, inline styles take precedence over CSS stylesheets so user-, skin- or device-specific customizations become more difficult.Yes! TemplateStyles includes a full-fledgedCSS parser that reads, re-serializes and escapes all code and removes CSS rules which it does not recognize. The parser is sufficiently fine-grained to reject remote resources (such as background images) but allow local ones. CSS selectors are rewritten so that they cannot refer to elements outside article content. (Visually modifying areas outside article content by displacing parts of the article, e.g. via absolute positioning, is not prevented at this time. This is no change from the status quo, as such a thing was already possible with wikitext and inline styles.)
As of 5 March 2025, TemplateStyles accepts no fewer than 331 CSS properties and aliases, including the vast majority of those most often used on the modern internet with official support by one or more major web browser.Beyond simple rules,@media,@page,@supports,@keyframe,@font-face/@font-feature-values at-rules are also supported (with font-face restricted to fonts whose name starts withTemplateStyles, for security reasons).
The CSSvar() function is permitted only in properties taking a single color value and insidecalc()functions.Setting custom properties is not permitted.
| CSS property declarations permitted by css-sanitizer[a][b][c] |
Note: Each property is linked to a source of documentation on its usage, however the typical external link icons have been suppressed to prevent the obscuring of any links to footnotes that similarly appear in superscript.
Notes:
|
Media queries allow you to target elements at mobile resolution and desktop resolution.Some advise making your styles mobile friendly by default and wrapping desktop styles within the media query.Note, MediaWikihas standardised on 640px and 1120px breakpoints to represent tablet and desktop.
MediaWiki provides various classes on thehtml andbody elements, including one that indicates which skin is in use.These can be targeted by including a simple selector for thehtml orbody element including the needed classes, followed by a space (or in CSS terms, the descendant combinator).
Generally, this technique should be used for design consistency, rather than targeting mobile and desktop as all skins can be used in both mobile and desktop resolutions.See also#How can I target mobile/desktop resolutions?.
/* Elements with class 'foo' will have red text in all skins. */.foo{color:red;}/* Override that element's color to green for the Vector skin only. */body.skin-vector.foo{color:green;}/* Add a red border if the browser doesn't have JavaScript enabled. */html.client-nojs.foo{border:1pxsolidred;}/* Declare that same border as green for the Vector skin. */html.client-nojsbody.skin-vector.foo{border-color:green;}
/* This does not work; the 'body' element must be selected! */.skin-vector.foo{background:orange;}/* These do not work, either; the descendant combinator must be used. */body.skin-vector>.foo{background:orange;}body.skin-vector~.foo{background:orange;}html.client-nojs>body.skin-vector.foo{background:orange;}
To prevent a malicious user from messing with the parts of the document outside the main content area, all CSS rules automatically get prefixed by themw-parser-output CSS class.If you use a TemplateStyles-based template outside of the content area (e.g. in thesitenotice), you need to provide that class yourself, by wrapping the template in something like<divclass="mw-parser-output">…</div>.
Which CSS rule takes effect is controlled byspecificity (roughly, the complexity of the selector - e.g.div.foo{margin:10px} is more specific than.foo{margin:5px}).In case of equal specificity, CSS styles that come later in the document override earlier styles.
MediaWiki:Common.css, other site scripts, user scripts and gadgets are loaded in the<head> section of the page.TemplateStyles stylesheets are loaded in the<body>, so they override site/user script and gadget rules with equal specificity, and in the case of two TemplateStyles rules, the second overrides the first.(Note though that TemplateStyles rules are deduplicated: if the same stylesheet is referenced multiple times on the page, it is only inserted the first time.
Note also that "later" has to do with document position, not load order.Gadgets add their CSS after the page has fully loaded, by manipulating the page with JavaScript; some add it on-demand when the user does some action such as clicking a button.Nevertheless, they add it to the head, so equally-specific CSS rules in the body get precedence over it.)
TemplateStyles can be called from a Lua module usingframe:extensionTag.
Example code is the following:
localp={};functionp.templateStyle(frame,src)returnframe:extensionTag('templatestyles','',{src=src});endreturnp;
The design choice to store CSS in separate pages was made in part to make integration with the standard anti-abuse toolset easy. TemplateStyles CSS pages have their own content model (sanitized-css) so changes to them can be tracked or controlled withExtension:AbuseFilter, using thenew_content_model variable.
CSS inclusion is tracked the same way as template transclusion, so you can see where a stylesheet is used via the "What links here" option, see what stylesheets are used on a page under "Page information" (and possibly on the edit screen, depending on what editor you use), and see what recent changes might be affecting a page using "Related changes".
TemplateStyles also leaves identifying information in the HTML code; to find out where a specific rule comes from, look at the page source, and the enclosing<style> tag will have an attribute likedata-mw-deduplicate="TemplateStyles:r123456", where 123456 is the revision ID of the stylesheet (viewable withSpecial:Diff, for example).
The idea of including CSS with templates was proposed and accepted in arequest for comments. Technical details were pinned down ina second RfC and workflow details were expanded through auser consultation.
TemplateStyles was originally a project of theWikimedia Reading Infrastructure team (preceded by exploratory workCoren did as a volunteer), consisting ofBrad Jorsch (developer),Bryan Davis (manager) andGergő Tisza (developer) at the time. People and responsibilities have since moved around; see themaintainers page for current ownership.
Pleasefile tasks under the TemplateStyles component inPhabricator.
You can look at somecurated examples.
The feature is enabled on all Wikimedia sites.
If you receive the following error when trying to publish the changes to your CSS file:
background-image at line$1 character$2.It could be that theurl('...'); attribute given tobackground-image is not pointing to a local resource.The parser only allows local resources (and rejects remote ones).Only URLs which point to resources at//upload.wikimedia.org/ are permitted, for example//upload.wikimedia.org/wikipedia/commons/8/83/MediaWiki-2023-button-proposal.svg for the file atFile:MediaWiki-2023-button-proposal.svg.These URLs can be obtained by using the URL address that links point to onWikimedia Commons file pages.These links include those to "Original file" or any of the links to the file's "Other resolutions:" such as1,024 × 1,024 pixels.