Help:TemplateStyles
TemplateStyles enables the complex behavioral and aesthetic styling of templates 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 for autoconfirmed users and so doesn't require involving someone with interface administrator privileges.
How does it work?
[edit ]Editors can add <templatestyles src="[some page]" />
to a page and the contents of the referenced page will be parsed as CSS, 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 the sanitized-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 for Template:Foo
in a subpage of the template they're most impactful upon, such as Template:Foo/styles.css
.
If [some page]
lacks a namespace prefix, it defaults to the Template namespace. Thus, for example, <templatestyles src="Foo/styles.css" />
will load Template: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 potential flash of unstyled content if the page becomes initially visible while still only partially rendered.
What problems does it solve?
[edit ]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 as TemplateSandbox ) 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 constituting more 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:
- Using inline styles (that is, raw HTML code with added attributes like
style="margin: 10px;"
) - Using certain special system messages such as MediaWiki:Common.css
For inline styling
[edit ]- There is no separation of content and presentation. In cases where the content does not come from a template (e.g. tables in articles), that will result in article wikitext that's unintelligible for most editors.
- Since styles are mixed with wikitext, syntax highlighting and other forms of CSS editing support are difficult or impossible.
- Styles have to be repeated for each HTML element they apply to, which results in lots of copy-pasting and code that is hard to read and maintain.
- Style attributes are limited to a subset of CSS. Most importantly,
@media
rules needed for responsive 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.
For system pages (MediaWiki:*.css)
[edit ]- Editing is limited to interface administrators , which is a major barrier to participation.
- Editing restrictions cannot be lifted as there is no way to limit what CSS rules can be used, and some of them could be abused to track readers' IP addresses or even execute scripts in some older browsers.
- Changes are impossible to test without saving first. T112474
- All stylesheets must be loaded on all pages (whether they actually use the page or not), which wastes bandwidth and makes debugging style rules harder.
Is it safe?
[edit ]Yes! TemplateStyles includes a full-fledged CSS 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.)
Allowed CSS properties and rules
[edit ]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 with TemplateStyles
, for security reasons).
- align-*
animation
appearance
aspect-ratio
background
- block-*
border
bottom
- box-*
- break-* [e]
caption-side
caret
clear
clip
[f]color
columns
- contain-*
content
continue
[h]- counter-*
counter-increment
counter-reset
cursor
direction
display
empty-cells
filter
flex
float
- flood-*
font
gap
[j]grid
hanging-punctuation
height
hyphens
- image-*
inline-size
inset
[k]isolation
- justify-*
left
letter-spacing
lighting-color
- line-*
list-style
margin
mask
- max-*
max-lines
- min-*
min-intrinsic-sizing
mix-blend-mode
- nav-*
- object-*
- offset-* [k]
offset-anchor
offset-position
offset-path
offset-distance
offset-rotate
(削除) offset-after (削除ここまで)(削除) offset-before (削除ここまで)(削除) offset-end (削除ここまで)(削除) offset-start (削除ここまで)
opacity
order
orphans
outline
overflow
padding
- page-break-* [e]
- place-*
position
quotes
resize
right
row-gap
[m]- shape-*
tab-size
table-layout
- text-*
top
transform
transition
unicode-bidi
user-select
vertical-align
visibility
white-space
widows
width
word-break
word-spacing
writing-mode
z-index
Notes:
- ↑ This list is current as of changeset ffe10a21512f to the css-sanitizer source code repository, authored at 20:34, 5 March 2025.
- ↑ The authoritative reference for these properties will always be the source code for the Css-sanitizer library, specifically the
src/Sanitizer/StylePropertySanitizer.php
file. When reviewing it, a simple method for bringing them into greater focus is to perform a full text search of the contents for the string$props
. - ↑ Non-standard properties—including those with vendor prefixes, except for the vendor-prefixed
-*-user-select
group—have never been recognized by this extension and continue to be automatically rejected, as of January 2024; see T162379: Decide which non-standard CSS properties to support in TemplateStyles for notice of any progress on a resolution to this issue. - ↑ The modern
block-ellipsis
property is present in the extension source code only by its original name,block-overflow
(Line 676 at changeset ffe10a21512f). Though the property was renamed during drafting by the W3C-CSSWG in August 2018 and is now only a legacy alias, until the extension is updated only the original property name is accepted as valid. - ↑ 5.0 5.1 5.2 5.3 5.4 5.5 5.6 5.7 The
page-break-*
properties from CSS2 were deprecated by the W3C-CSSWG in September 2018 and persist only as legacy shorthands for thebreak-*
replacement properties from the CSS3 Fragmentation module. They are subject to removal in the future and users are strenuously encouraged to replace all uses of the older properties explicitly, paying attention to the fact that not all values have a 1:1 equivalent mapping with the replacements' values. Several popular user agents have already demonstrated flawed and inconsistent behavior when the legacy shorthands are present on a page. - ↑ The
(削除) clip (削除ここまで)property was deprecated by the W3C-CSSWG in July 2018, and official guidance was added to use theclip-path
property in its place; it is subject to removal at any time due to definition conflicts with other properties. - ↑ The legacy name alias
grid-column-gap
is also accepted as valid by this extension and is evaluated exactly as if its modern replacement property name,column-gap
, had been used. - ↑ The modern
continue
property, which is accepted by this extension, must always be used in place of the olderregion-fragment
property, which it never accepted as valid. The W3C-CSSWG describes 'continue' as generalizing the older property ahead of replacing it altogether, but care must be taken during the conversion as different values must be defined to achieve identical behaviors between the two. - ↑ The modern
font-width
property is present in the extension source code only by its original name,font-stretch
(Line 543 at changeset ffe10a21512f). Though the original name was deprecated by the W3C-CSSWG in January 2024 and remains only as a legacy alias, until the extension is updated only the original property name is accepted as valid. - ↑ The legacy name alias
grid-gap
is also accepted as valid by this extension and is evaluated exactly as if its modern replacement property name,gap
, had been used. - ↑ 11.0 11.1 The offset-* properties were renamed
inset-*
in March 2025 by the W3C-CSSWG in the CSS Position 3 module, which supersedes and replaces CSS Logical 1. The 'flow-relative offsets' are now renamed in concordance:inset-block-start
,inset-block-end
,inset-inline-start
,inset-inline-end
properties andinset-block
,inset-inline
, andinset
shorthands. The deprecated offset-* properties should be distinguished from the still extantoffset-*
shorthands,offset-anchor
,offset-position
,offset-path
,offset-distance
, andoffset-rotate
. - ↑ The non-standard property,
word-wrap
, is also accepted as valid by this extension and is directly aliased to the official propertyoverflow-wrap
. - ↑ The legacy name alias
grid-row-gap
is also accepted as valid by this extension and is evaluated exactly as if its modern replacement property name,row-gap
, had been used. - ↑ 14.0 14.1 Though the creation of the
text-align-all
property as a constituent value of thetext-align
shorthand by the W3C-CSSWG took place in December 2018, supporting implementations did not begin appearing until 2025 and, as of the most recent official guidance on March 24, 2025, the recommendation to eschew the new property and continue to use the shorthand remains in effect.
How can I target mobile/desktop resolutions?
[edit ]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, MediaWiki has standardised on 640px and 1120px breakpoints to represent tablet and desktop.
How can I target specific skins?
[edit ]MediaWiki provides various classes on the html
and body
elements, including one that indicates which skin is in use.
These can be targeted by including a simple selector for the html
or body
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;}
How do I use styles in MediaWiki messages?
[edit ]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 the mw-parser-output
CSS class.
If you use a TemplateStyles-based template outside of the content area (e.g. in the sitenotice ), you need to provide that class yourself, by wrapping the template in something like <div class="mw-parser-output">...</div>
.
In which order do CSS styles override?
[edit ]Which CSS rule takes effect is controlled by specificity (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.)
How can Lua modules interact with styles?
[edit ]TemplateStyles can be called from a Lua module using frame:extensionTag
.
Example code is the following:
localp={}; functionp.templateStyle(frame,src) returnframe:extensionTag('templatestyles','',{src=src}); end returnp;
What anti-abuse features are provided?
[edit ]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 with Extension:AbuseFilter , using the new_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 like data-mw-deduplicate="TemplateStyles:r123456"
, where 123456 is the revision ID of the stylesheet (viewable with Special:Diff, for example).
How were the decisions around TemplateStyles made?
[edit ]The idea of including CSS with templates was proposed and accepted in a request for comments. Technical details were pinned down in a second RfC and workflow details were expanded through a user consultation.
Who is working on TemplateStyles?
[edit ]TemplateStyles was originally a project of the Wikimedia Reading Infrastructure team (preceded by exploratory work Coren did as a volunteer), consisting of Brad Jorsch (developer), Bryan Davis (manager) and Gergő Tisza (developer) at the time. People and responsibilities have since moved around; see the maintainers page for current ownership.
Where do I report errors / ask for features?
[edit ]Please file tasks under the TemplateStyles component in Phabricator.
Where can I see it in action?
[edit ]You can look at some curated examples.
The feature is enabled on all Wikimedia sites.
Help with errors
[edit ]background-image
[edit ]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 the url('...');
attribute given to background-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 at File:MediaWiki-2023-button-proposal.svg.
These URLs can be obtained by using the URL address that links point to on Wikimedia Commons file pages.
These links include those to "Original file" or any of the links to the file's "Other resolutions:" such as 1,024 ×ばつ 1,024 pixels
.
See also
[edit ]- Extension:TemplateStyles – especially the #Caveats section.
- Wikipedia:TemplateStyles – guideline page on English Wikipedia.