Movatterモバイル変換


[0]ホーム

URL:


Jump to content
MediaWiki
Search

Help:TemplateStyles

From mediawiki.org
Translate this page
Languages:
PDNote: When you edit this page, you agree to release your contribution under theCC0. SeePublic Domain Help Pages for more info.PD

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.

How does it work?

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.

What problems does it solve?

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:

  • Using inline styles (that is, raw HTML code with added attributes likestyle="margin: 10px;")
  • Using certain special system messages such asMediaWiki:Common.css

For inline styling

  • 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 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.

For system pages (MediaWiki:*.css)

  • Editing is limited tointerface 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?

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.)

Allowed CSS properties and rules

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:

  1. This list is current as of changesetffe10a21512f to the css-sanitizersource code repository, authored at 20:34, 5 March 2025.
  2. The authoritative reference for these properties will always be the source code for theCss-sanitizer library, specifically thesrc/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.
  3. 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; seeT162379:Decide which non-standard CSS properties to support in TemplateStyles for notice of any progress on a resolution to this issue.
  4. The modernblock-ellipsis property is present in the extension source code only by its original name,block-overflow (Line 676 at changeset ffe10a21512f). Though the property wasrenamed during drafting by theW3C-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. 5.05.15.25.35.45.55.65.7Thepage-break-* properties from CSS2 weredeprecated by theW3C-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.
  6. Theclip property wasdeprecated by theW3C-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.
  7. The legacy name aliasgrid-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.
  8. The moderncontinue property, which is accepted by this extension, must always be used in place of the olderregion-fragment property, which it never accepted as valid. TheW3C-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.
  9. The modernfont-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 wasdeprecated by theW3C-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.
  10. The legacy name aliasgrid-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. 11.011.1Theoffset-* properties wererenamedinset-* in March 2025 by theW3C-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 deprecatedoffset-*properties should be distinguished from the still extantoffset-*shorthands,offset-anchor,offset-position,offset-path,offset-distance, andoffset-rotate.
  12. The non-standard property,word-wrap, is also accepted as valid by this extension and is directly aliased to the official propertyoverflow-wrap.
  13. The legacy name aliasgrid-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. 14.014.1Though the creation of thetext-align-all property as a constituent value of thetext-align shorthand by theW3C-CSSWG took place in December 2018, supporting implementations did not beginappearing until 2025 and, as of the most recent official guidance onMarch 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?

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.

How can I target specific skins?

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;}

How do I use styles in MediaWiki messages?

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>.

In which order do CSS styles override?

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.)

How can Lua modules interact with styles?

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;

What anti-abuse features are provided?

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).

How were the decisions around TemplateStyles made?

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.

Who is working on TemplateStyles?

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.

Where do I report errors / ask for features?

Pleasefile tasks under the TemplateStyles component inPhabricator.

Where can I see it in action?

You can look at somecurated examples.

The feature is enabled on all Wikimedia sites.

Help with errors

background-image

If you receive the following error when trying to publish the changes to your CSS file:

Invalid or unsupported value for propertybackground-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.

See also

Retrieved from "https://www.mediawiki.org/w/index.php?title=Help:TemplateStyles&oldid=7994453"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp