Příručka:Kódovací konvence/CSS
![]() | Tato stránka dokumentuje pokyny pro vývoj MediaWiki, vytvořené v průběhu času na základě konsenzu vývojářů (nebo někdy na základě prohlášení hlavního vývojáře) |
Tato stránka popisuje kódovací konvence pro styly CSS a LESS v MediaWiki codebase.
Odkazování
Jako nástroj pro kvalitu kódu používáme stylelint s vlastní konfigurací pro Wikimedii (stylelint-config-wikimedia).
K lintování CSS nebo LESS můžete použít modul uzlu grunt-stylelint
. MediaWiki a většina rozšíření ji spouští jako součást continuous integration .
Nastavení jádra MediaWiki najdete v .stylelintrc.json
.
Pojmenovávání
Třídy pojmenujte stejným způsobem: Všechna písmena malá a slova rozdělená pomlčkami.
V jádru MediaWiki používejte předponu mw-
, abyste se vyhnuli konfliktům s názvy tříd a ID vytvořenými uživateli ze šablon wikitextu, nadpisů sekcí, gadgetů a dalších softwarových knihoven.
Kde je to možné, vyhněte se zavádění ID a místo toho používejte třídy CSS.
Příklady použití:
/* Prvky na celém webu */
.mw-body,
.mw-headline,
.mw-label,
.mw-input {
}
/* Speciální stránky */
.mw-body-content,
/* - Special:AllPages */
.mw-allpages-table-form,
.mw-allpages-nav {
}
Všimněte si, že slova jsou rozdělena pomlčkami, aby se zjednodušila čitelnost kódu pro nerodilé mluvčí angličtiny a aby programátorům, kteří spoléhají na asistenční technologii, poskytla lepší zkušenost, například výstup pro čtečku obrazovky.
.mw-allpages-table-form
je historický název třídy, který se datuje před výše uvedenou radou. Podle této by to bylo .mw-all-pages-table-form
.
V rozšířeních a vzhledech použijte předponu ext-my-extension-name-
nebo skin-my-skin-name-
.
Příklady použití:
.ext-discussiontools-ui-targetWidget {
}
.ext-ipinfo-infobox {
}
.skin-vector-toc-experiment-treatment {
}
.skin-minerva--talk-simplified {
}
Konstruované názvy tříd
Při dynamickém vytváření názvů tříd v kódu se ujistěte, že je výše umístěn komentář, který uvádí všechny možné názvy tříd. Viz také Příručka:Konvence kódování#Dynamické identifikátory. Například:
// Používají se zde následující třídy:
// * mw-editfont-monospace
// * mw-editfont-sans-serif
// * mw-editfont-serif
$class = 'mw-editfont-' . $userOptionsLookup->getOption( $user, 'editfont' );
Specifičnost
Poskytněte selektory s co možná nízkou specifitou, pokud možno jeden selektor třídy modulu. To zjednodušuje jejich přepisování v konkrétních kontextech, jako jsou určitá rozšíření nebo uživatelské skripty.
Vpravo (nízká specifičnost): | Špatně (překonkrétní, vázaný prvek HTML): |
---|---|
.mw-bar {
border-radius: 2px;
}
.mw-foo {
background-color: #fff;
}
|
div#mw-bar-zero {
border-radius: 2px;
}
div#mw-foo-one {
background-color: #fff;
}
|
Mezery
Milujeme mezery:
- Jeden selektor na řádek.
- Jedno prohlášení o vlastnosti na řádek.
- Otevírací složené závorky pro blok deklarace CSS na stejném řádku jako (poslední) selektor.
- Otevírací složené závorky pro blok deklarace CSS na stejném řádku jako (poslední) selektor.
- Žádná mezera před dvojtečkou (
:
). - Jedna mezera za dvojtečkou a před hodnotou.
- Jedna mezera za čárkami (
,
) ve vlastnostech s více hodnotami. - One space after a starting and before an ending parentheses (
(
and)
) in selectors (ex.:not()
) and properties (ex.rgba()
). - Středník (
;
) za každou deklarací (včetně poslední). - Zavírací závorky odsazeny zpět doleva.
- Annotation for CSSJanus and CSSMin should be on their own line, above the CSS declaration they're for.
- Prázdný řádek mezi jednou sadou pravidel CSS a další.
.mw-selector,
.mw-some-element input[ type='text' ] {
background-color: #fff;
color: #202122;
float: right;
font-family: sans-serif;
text-align: left;
transform: scale( 1.2 );
}
/* Příklad, který používá anotace CSSJanus a CSSMin */
.mw-look-at-the-left {
/* @embed */
background-image: url( images/foobar.svg );
/* @noflip */
float: left;
}
Citáty
Wikimedie používá jednoduché uvozovky pro hodnoty, které vyžadují citaci.
Například hodnoty vlastnosti CSS content
a v selektorech atributů.
Uvozovky jsou v parametru url()
deklarace background-image
zbytečné.
Jediným případem, kdy by to mohlo způsobit problémy, je situace, kdy se v cestě objeví neescapovaná uzavírací závorka. V takovém případě byste měli takové znaky v URL vynechat.
Hodnoty vlastností barev
CSS3 supports many different kinds of color values for CSS properties like background-color
, color
, border-color
, et al.
Pro konzistenci a kompatibilitu používejte pouze tyto tři:
- Hexadecimální hodnoty barev jako
#fff
a#f8f9fa
. (Use lowercase for better gzip compression![1] Use shorthand notation when possible.) - Hodnoty
rgba()
, pokud je vyžadována průhlednost alfa, napříkladrgba( 255, 255, 255, 0.5 )
. (Attention: IE8 doesn't supportrgba()
notation, so always provide a matching declaration before this one with a hex color value as fallback.) transparent
barevné klíčové slovo. (Attention: IE8 supports it only forbackground-color
andborder
. It drawscolor: transparent;
as black.)[2]
Upřednostňujte všechny hodnoty "malými písmeny" pro konzistenci a optimalizovanou kompresi souborů.[3]
Viz také sekce stránky Talk.
Vyhněte se jiným hodnotám barev (včetně názvů barev/klíčových slov – myslete na i18n, když si představíte zápisy burlywood
, rgb()
, hsl()
a hsla()
).
Také se ujistěte, že váš barevný kontrastní poměr popředí a pozadí (včetně přechodů pozadí a záložních barev) odpovídá WCAG 2.0 Level AA, ideálně Level AAA.[4]
Jednotky velikosti
Wikimedia Foundation aims to support a diverse audience and a wide range of technologies and use cases.
A very popular accessibility user setting is increasing browser default font size while providing the best design for average users.
It also reduces burden of em
calculation and predictability on developers to the absolute minimum.
Use px
for all elements, that are not directly affecting reading or understanding user-interface.
Mostly font-size
, line-height
, icon sizing by background-size
or padding
.
Název proměnné
CSS and LESS variables are set to follow a naming logic, going from repeating property to application usage to possible modifier or in short property-application[--modifier]
.
Variables are generally used for one property, like font-size
, there are very few variables that are able to be used in different contexts.
For example size variables @size-small
.
It's simpler, specifically in big projects with many CSS/LESS files to have single usage variables, even though that might result in a larger variables definition file.
See archived discussion for problem description.
It's also more fail-safe when the variable contents get changed (think of color
versus background-color
applications).
CSS variables example:
--background-color-error: #fff36f;
--color-error: #d33;
/* Přihlášení */
.mw-error {
background-color: var( --background-color-error );
color: var( --color-error );
}
LESS variables example:
/* Barvy a barvy pozadí */
@background-color-base: #fff;
@background-color-error: #fff36f;
@color-base: #000;
@color-error: #d33;
@color-progressive: #36c;
// Polohování
@position-selector: absolute;
@position-offset-selector: -4px;
/* Velikosti a model box */
@size-selector: 42rem; // Použijte pro hodnoty vlastností šířka i výška.
@border-color-error: @color-error;
@border-size-base: 1px;
@border-style-base: solid;
@border-error: @border-size-base @border-style-base @border-color-error;
/* Fonty */
@font-family-serif: 'Linux Libertine', Georgia, Times, serif;
@font-family-sans: sans-serif;
/* Přechody */
@transition-base: 200ms;
/* Přihlášení */
.mw-selector {
background-image: url( selector.svg );
background-repeat: no-repeat;
color: @color-error;
display: block;
position: @position-selector;
top: 0;
left: 0;
width: @size-selector;
height: @size-selector;
font-family: @font-family-sans;
}
Předpony dodavatele
Always put the standardized versions of CSS properties after vendor-prefixed versions.
It is important for avoiding bugs in old implementation, like in the following example of -webkit-border-radius
.
See also https://css-tricks.com/ordering-css3-properties/.
Správně: | Špatně v několika ohledech: |
---|---|
.bar {
-webkit-border-radius: 30px 10px;
border-radius: 30px 10px;
}
.foo {
background-color: #444;
background-image: -webkit-gradient( linear, left top, left bottom, from( #444 ), to( #999 ) );
background-image: -webkit-linear-gradient( top, #444, #999 );
background-image: -moz-linear-gradient( top, #444, #999 );
background-image: linear-gradient( to bottom, #444, #999 );
}
|
.bar {
border-radius: 30px 10px;
-webkit-border-radius: 30px 10px;
}
.foo {
background-image: linear-gradient(top, #444444, #999999);
background-image: -moz-linear-gradient(top, #444444, #999999);
background-image: -webkit-linear-gradient(top, #444444, #999999);
background-image: -webkit-gradient(linear, left top, left bottom, from(#444444), to(#999999));
}
|
Správně a včetně anotace:
/* Komentovaná verze */
.foo {
/* Fallback color in case background-image gradient is not supported */
background-color: #444;
/* Safari 4, Chrome 2, iOS 2 */
background-image: -webkit-gradient( linear, left top, left bottom, from( #444 ), to( #999 ) );
/* Safari 5.1+, Chrome 10+, iOS 5 */
background-image: -webkit-linear-gradient( top, #444, #999 );
/* Firefox 3.6 - 15 */
background-image: -moz-linear-gradient( top, #444, #999 );
/* Standard syntax supported by Firefox 16+, Opera 12.5+, IE10+ */
background-image: linear-gradient( to bottom, #444, #999 );
}
.client-js a .client-nojs
MediaWiki outputs class client-nojs
on the <html>
element on every page.
At runtime, JavaScript code replaces this with class client-js
.
Hence you can use this class in your selector to conditionally show, hide, or customize certain elements depending on whether the browser has JavaScript enabled and is supported by ResourceLoader .
Note that for this to be useful, the stylesheet in question must be loaded with OutputPage::addModuleStyles()
, not mw.loader
(see Developing with ResourceLoader )
Anti vzory
Anti-patterns are mostly covered by use of central 'stylelint-config-wikimedia' already. Please also see the inline comments on master. Beyond there are some special properties/functionalities that deserve further explanation.
Nespoléhejte na hodnoty založené na jednotkách px
This is not a general rule, but it is general for a few properties.
When a user increases their default font size preferences in a browser due to addressing visual impairments, a widely used accessibility feature, all sizes defined in px
are not scaled.
In order to let users scale text with this setting, rely on relative sizes like em
or rem
, specifically on properties that would result in non-scalable text like font-size or line-height or would overflow and be hidden, often with certain width or height limitations.
z-index
Avoid using z-index
when possible.
Instead, try to use the natural stacking order in the DOM.
When use of z-index is required, please use the appropriate Codex design token.
!important
Avoid using !important
(except for working around upstream code running on the same page that also uses !important
, because only !important
can override !important
).
In most cases you don't need it at all. In other cases it may be the result of a bug elsewhere in the program. In general, to override a rule you use the same selector as the original style rule. Since CSS cascades, this works naturally (styles applied later override styles applied earlier, selectors don't need to be of higher specificity).[5]
If the overriding styles apply before the original styles, the styles got loaded in the wrong order. That should be addressed, but you may resort to workarounds to artificially increase the specificity:
- Repeat the same selector to increase weight, like
.foo.foo
.[6] - Add or repeat attribute selectors, like
[class]
. - Use default elements as ancestor selector (e.g.
body .foo
,html body .foo
).
Add however many points you need. It will still allow multiple stylesheets to use the same technique and each express their specificity. Better than adding in ancestors classes not related to your code. (And more maintainable as they won't change.)
LESS
Starting with MediaWiki 1.22, there is native support in ResourceLoader for using LESS (with file extension .less
) in place of CSS.
Most of the LESS syntax can be formatted using the CSS conventions:
- Indent nested blocks with 1 tab (same as for indenting declarations inside CSS rules).
- Don't space-align declarations values inside mixins (same as for CSS rules).
- No spaces on the outside of the parameter lists in function invocations, mixin uses and mixin definitions (same as for
url( image.png )
in CSS). - No quotes around parameter values (same as for
url( image.png )
in CSS).
Example:
/*
* Do kódu nemusíte kopírovat '.background-image'.
* Poskytuje jej jádro MediaWiki (v mediawiki.less).
* Je zde jako příklad syntaxe guard.
*/
.background-image( @url ) when ( embeddable( @url ) ) {
background-image: embed( @url );
background-image: url( @url )!ie;
}
.background-image( @url ) when not ( embeddable( @url ) ) {
background-image: url( @url );
}
.mw-example {
.background-image( images/example.png );
border: 1px solid #a2a9b1;
padding: 4px 8px;
font-size: 1em;
.mw-example-thing {
display: inline-block;
/* @noflip */
float: left;
border: 1px solid #c8ccd1;
border-radius: 2px;
padding: 4px 8px;
}
}
There's a few new concepts that don't map to CSS conventions, outlined below.
Struktura
- Separate nested CSS rules from the parent declarations by 1 empty line.
@noflip
tags must be on the line immediately above the declaration, as shown in the example above.
Import souborů LESS/CSS
- The filename of an import statement has to include the
.less
file extension.- If the extension was omitted, in a folder with 'foo.css' and 'foo.less' LESS would import the latter.
- If the code is ever used outside MediaWiki context, for example in Webpack as part of storybook, it will throw an error as it will assume it is a package with an index.css or index.js file meaning the code cannot be used.
- Use
@import
to load mixins and variables so that they may be used by the current LESS stylesheet; these are processed synchronously by LESS and will not be present in the generated CSS output. Load mixins first, variables second. Mixins should be free of variable values and parameters in mixin calls provide values with variables. - Don't use
@import
to bundle stylesheets that are related to one another only conceptually; instead, reference the set of files in thestyles
array of a ResourceLoader module. - Don't use
@import
to import CSS files in LESS files, as the LESS parser will create an invalid import statement based on the physical location of the CSS file. Use@import (inline)
instead.
Odstraňování problémů s importem
If your LESS @import
doesn't work please check:
- Does your code contain
@font-face
? See this question on Stack Overflow about how to use @font-face with LESS.
Mixins
Mixin names should use hyphen-case, just like CSS class names, property keys and variable names.
They should be prefixed with mixin-
to avoid confusing developers who are familiar with CSS, but not LESS and distinguish them from classes, the syntax for which is similar.
As mentioned above, no spaces on the outside of the parameter list and avoid quoting values.
If you need to call a mixin with one or more arguments that contain a comma use a semicolon ;
in LESS to separate the arguments.
This allows you to use commas in the literal value.
.mixin-example( @function, @properties ) {
transition-timing-function: @function;
transition-property: @property;
}
Vestavěné mixiny
mediawiki.mixins.less is a LESS library maintained as part of MediaWiki that is automatically available to any LESS stylesheet in MediaWiki. It can be imported from any LESS stylesheet in core, skins, and extensions.
@import 'mediawiki.mixins.less';
.my-create-link {
.background-image-svg( 'images/create_normal.svg', 'images/create_normal.png' );
/* Protože '.background-image-svg' přebírá dva parametry, musí být uzavřeny v uvozovkách */
}
Since MediaWiki 1.27 , the built-in mixins contain utilities for using CSS Flexbox. Support is present all browsers that implemented at least one of the specs, including Internet Explorer 10. You need to specify your own fallback for older browsers, e.g. you can use floats for a more basic experience. Mixins available:
// Poskytuje 'mediwiki.mixins':
.flex-display( @display: flex );
.flex-wrap( @wrap: wrap );
.flex( @grow: 1, @shrink: 1, @width: auto, @order: 1 );
Example usage:
@import 'mediawiki.mixins.less';
.my-container {
.flex-display();
}
.my-left {
.flex( 0, 0, auto, 1 );
}
.my-right {
.flex( 0, 0, auto, 3 );
}
.my-center {
.flex( 1, 1, auto, 2 );
}
Aplikováno správně: | Špatně použito: |
---|---|
.mw-example {
.mixin-example( ease-in-out; opacity, color );
/* Rozbalí se na: */
transition-timing-function: ease-in-out;
transition-property: opacity, color;
}
|
.mw-example {
.mixin-example( 'ease-in-out', 'opacity, color' );
/* Rozbalí se na: */
transition-timing-function: 'ease-in-out';
transition-property: 'opacity, color';
/* Hodnoty zahrnují uvozovky, jedná se o neplatné CSS a vede k tomu, že prohlížeč tyto vlastnosti ignoruje */
}
/* Další špatný příklad: */
.mw-example {
.mixin-example( ~'ease-in-out', ~'opacity, color' );
/* Rozbalí se na: */
transition-timing-function: ease-in-out;
transition-property: opacity, color;
/* Operátor '~' dává Lessovi pokyn, aby hodnoty zrušil.
* To vytváří dobré CSS, ale tomuto vzoru se vyhýbáme ve prospěch důsledného používání ';'.
*/
}
|
Poznámky pod čarou
- ↑ https://www.websiteoptimization.com/speed/tweak/lowercase/
- ↑ Color value browser compatibility, see notes
- ↑ Značení malými písmeny má menší výstup gzip, HTML5 Boilerplate 2015
- ↑ WCAG 2.0 Porozumění kontrastu
- ↑ Specifics on CSS Specificity, css-tricks.com
- ↑ 3.14 things I didn’t know about CSS, CSS Day Conference 2014