Help:TemplateStyles/pt

PD Nota: Quando modificais esta página, estais a aceitar que a vossa contribuição se publique no marco de CC0. Olhem Páginas de ajuda de domínio público para mais informação. PD

TemplateStyles permite o complexo comportamento e estilo estético das predefinições através da utilização de ficheiros CSS externos referenciados que são as próprias páginas wiki. Notavelmente, a funcionalidade de criar ou modificar os ficheiros CSS está incluída nas permissões predefinidas para usuários auto-confirmados e por isso, não é necessário envolver alguém com privilégios de administrador de interface.

Como é que funciona?

Os editores podem adicionar <templatestyles src="[alguma página]" /> a uma página e o conteúdo da página referenciada será interpretado como CSS, higienizado e carregado em páginas onde a etiqueta <templatestyles> é usada (diretamente ou transcluída por uma predefinição em uso na página).

[alguma página] deve ter o modelo de conteúdo sanitized-css (CSS higienizado), que é o padrão para subpáginas no espaço do nome Template que terminam com .css. O padrão de uso recomendado é criar os estilos para Template:Foo numa subpágina da predefinição onde eles têm mais impacto, como Template:Foo/styles.css. Se [alguma página] não tiver um prefixo de espaço do nome, o padrão é o espaço do nome Template. Assim, por exemplo, <templatestyles src="Foo/styles.css" /> carregará Template:Foo/styles.css.

A etiqueta <templatestyles> deve ser colocada antes do conteúdo que é estilizado, idealmente no topo da predefinição ou o mais próximo possível, para evitar um potencial aparecimento de conteúdo não estilizado se a página tornar-se inicialmente visível quando estiver apenas parcialmente renderizada.

Quais os problemas que resolve?

O TemplateStyles permite que os editores associem regras de estilo a páginas específicas, fornece todo o potencial das folhas de estilo CSS, mas filtrando construções perigosas, e funciona com ferramentas de pré-visualização/depuração (como o TemplateSandbox) como esperado.

Espera-se que a redução das barreiras de acesso e atualização resultará em mais inovação na maneira em que as predefinições são visualmente concebidas, menos despesas de manutenção e melhor adaptabilidade pelas diversas configurações de ecrã (especialmente tendo em conta que os dispositivos móveis constituem mais de metade das visualizações de página da Wikipédia, a partir de março 2016).

Por norma, havia duas formas de estilizar predefinições (ou qualquer outro conteúdo) nas páginas do MediaWiki, e nenhuma delas funcionava muito bem:

  • Utilização dos estilos em linha (ou seja, código HTML em bruto com mais atributos como style="margin: 10px;")
  • Usando certas mensagens especiais do sistema, como MediaWiki:Common.css

Para estilo em linha

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

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

As of 5 de março de 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).

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, MediaWiki has standardised on 640px and 1120px breakpoints to represent tablet and desktop.

How can I target specific skins?

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: 1px solid red; }

/* Declare that same border as green for the Vector skin. */
html.client-nojs body.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 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?

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?

TemplateStyles can be called from a Lua module using frame:extensionTag.

Example code is the following:

local p = {};

function p.templateStyle( frame, src )
    return frame:extensionTag( 'templatestyles', '', { src = src } );
end

return p;

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 with Extension:Filtro de Abuso, 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 "Páginas afluentes" option, see what stylesheets are used on a page under "Informações da página" (and possibly on the edit screen, depending on what editor you use), and see what recent changes might be affecting a page using "Alterações relacionadas".

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?

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?

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?

Please file tasks under the TemplateStyles component in Phabricator.

Where can I see it in action?

You can look at some curated examples.

The feature is enabled on all Wikimedia sites.

See also

Category:Help/pt
Category:Help/pt