├── README.md
└── translations
├── cs-CZ
└── README.md
├── da-DK
└── README.md
├── de-DE
└── README.md
├── es-ES
└── README.md
├── fr-FR
└── README.md
├── id-ID
└── README.md
├── it-IT
└── README.md
├── ja-JP
└── README.md
├── ko-KR
└── README.md
├── nl-NL
└── README.md
├── pl-PL
└── README.md
├── pt-BR
└── README.md
├── ru-RU
└── README.md
├── sr-SR
└── README.md
├── tr-TR
└── README.md
├── zh-CN
└── README.md
└── zh-TW
└── README.md
/README.md:
--------------------------------------------------------------------------------
1 | # Principles of writing consistent, idiomatic CSS
2 |
3 | The following document outlines a reasonable style guide for CSS development.
4 | These guidelines strongly encourage the use of existing, common, sensible
5 | patterns. They should be adapted as needed to create your own style guide.
6 |
7 | This is a living document and new ideas are always welcome. Please
8 | contribute.
9 |
10 |
11 | ## Table of contents
12 |
13 | 1. [General principles](#general-principles)
14 | 2. [Whitespace](#whitespace)
15 | 3. [Comments](#comments)
16 | 4. [Format](#format)
17 | 5. [Practical example](#example)
18 |
19 | [Acknowledgements](#acknowledgements)
20 |
21 | [License](#license)
22 |
23 |
24 |
25 | ## 1. General principles
26 |
27 | > "Part of being a good steward to a successful project is realizing that
28 | > writing code for yourself is a Bad Idea™. If thousands of people are using
29 | > your code, then write your code for maximum clarity, not your personal
30 | > preference of how to get clever within the spec." - Idan Gazit
31 |
32 | * Don't try to prematurely optimize your code; keep it readable and
33 | understandable.
34 | * All code in any code-base should look like a single person typed it, even
35 | when many people are contributing to it.
36 | * Strictly enforce the agreed-upon style.
37 | * If in doubt when deciding upon a style use existing, common patterns.
38 |
39 |
40 |
41 | ## 2. Whitespace
42 |
43 | Only one style should exist across the entire source of your code-base. Always
44 | be consistent in your use of whitespace. Use whitespace to improve
45 | readability.
46 |
47 | * _Never_ mix spaces and tabs for indentation.
48 | * Choose between soft indents (spaces) or real tabs. Stick to your choice
49 | without fail. (Preference: spaces)
50 | * If using spaces, choose the number of characters used per indentation level.
51 | (Preference: 4 spaces)
52 |
53 | Tip: configure your editor to "show invisibles" or to automatically remove
54 | end-of-line whitespace.
55 |
56 | Tip: use an [EditorConfig](http://editorconfig.org/) file (or equivalent) to
57 | help maintain the basic whitespace conventions that have been agreed for your
58 | code-base.
59 |
60 |
61 |
62 | ## 3. Comments
63 |
64 | Well commented code is extremely important. Take time to describe components,
65 | how they work, their limitations, and the way they are constructed. Don't leave
66 | others in the team guessing as to the purpose of uncommon or non-obvious
67 | code.
68 |
69 | Comment style should be simple and consistent within a single code base.
70 |
71 | * Place comments on a new line above their subject.
72 | * Keep line-length to a sensible maximum, e.g., 80 columns.
73 | * Make liberal use of comments to break CSS code into discrete sections.
74 | * Use "sentence case" comments and consistent text indentation.
75 |
76 | Tip: configure your editor to provide you with shortcuts to output agreed-upon
77 | comment patterns.
78 |
79 | Example:
80 |
81 | ```css
82 | /* ==========================================================================
83 | Section comment block
84 | ========================================================================== */
85 |
86 | /* Sub-section comment block
87 | ========================================================================== */
88 |
89 | /**
90 | * Short description using Doxygen-style comment format
91 | *
92 | * The first sentence of the long description starts here and continues on this
93 | * line for a while finally concluding here at the end of this paragraph.
94 | *
95 | * The long description is ideal for more detailed explanations and
96 | * documentation. It can include example HTML, URLs, or any other information
97 | * that is deemed necessary or useful.
98 | *
99 | * @tag This is a tag named 'tag'
100 | *
101 | * TODO: This is a todo statement that describes an atomic task to be completed
102 | * at a later date. It wraps after 80 characters and following lines are
103 | * indented by 2 spaces.
104 | */
105 |
106 | /* Basic comment */
107 | ```
108 |
109 |
110 |
111 | ## 4. Format
112 |
113 | The chosen code format must ensure that code is: easy to read; easy to clearly
114 | comment; minimizes the chance of accidentally introducing errors; and results
115 | in useful diffs and blames.
116 |
117 | * Use one discrete selector per line in multi-selector rulesets.
118 | * Include a single space before the opening brace of a ruleset.
119 | * Include one declaration per line in a declaration block.
120 | * Use one level of indentation for each declaration.
121 | * Include a single space after the colon of a declaration.
122 | * Use lowercase and shorthand hex values, e.g., `#aaa`.
123 | * Use single or double quotes consistently. Preference is for double quotes,
124 | e.g., `content: ""`.
125 | * Quote attribute values in selectors, e.g., `input[type="checkbox"]`.
126 | * _Where allowed_, avoid specifying units for zero-values, e.g., `margin: 0`.
127 | * Include a space after each comma in comma-separated property or function
128 | values.
129 | * Include a semi-colon at the end of the last declaration in a declaration
130 | block.
131 | * Place the closing brace of a ruleset in the same column as the first
132 | character of the ruleset.
133 | * Separate each ruleset by a blank line.
134 |
135 | ```css
136 | .selector-1,
137 | .selector-2,
138 | .selector-3[type="text"] {
139 | -webkit-box-sizing: border-box;
140 | -moz-box-sizing: border-box;
141 | box-sizing: border-box;
142 | display: block;
143 | font-family: helvetica, arial, sans-serif;
144 | color: #333;
145 | background: #fff;
146 | background: linear-gradient(#fff, rgba(0, 0, 0, 0.8));
147 | }
148 |
149 | .selector-a,
150 | .selector-b {
151 | padding: 10px;
152 | }
153 | ```
154 |
155 | #### Declaration order
156 |
157 | If declarations are to be consistently ordered, it should be in accordance with
158 | a single, simple principle.
159 |
160 | Smaller teams may prefer to cluster related properties (e.g. positioning and
161 | box-model) together.
162 |
163 | ```css
164 | .selector {
165 | /* Positioning */
166 | position: absolute;
167 | z-index: 10;
168 | top: 0;
169 | right: 0;
170 | bottom: 0;
171 | left: 0;
172 |
173 | /* Display & Box Model */
174 | display: inline-block;
175 | overflow: hidden;
176 | box-sizing: border-box;
177 | width: 100px;
178 | height: 100px;
179 | padding: 10px;
180 | border: 10px solid #333;
181 | margin: 10px;
182 |
183 | /* Other */
184 | background: #000;
185 | color: #fff;
186 | font-family: sans-serif;
187 | font-size: 16px;
188 | text-align: right;
189 | }
190 | ```
191 |
192 | Larger teams may prefer the simplicity and ease-of-maintenance that comes with
193 | alphabetical ordering.
194 |
195 | #### Exceptions and slight deviations
196 |
197 | Large blocks of single declarations can use a slightly different, single-line
198 | format. In this case, a space should be included after the opening brace and
199 | before the closing brace.
200 |
201 | ```css
202 | .selector-1 { width: 10%; }
203 | .selector-2 { width: 20%; }
204 | .selector-3 { width: 30%; }
205 | ```
206 |
207 | Long, comma-separated property values - such as collections of gradients or
208 | shadows - can be arranged across multiple lines in an effort to improve
209 | readability and produce more useful diffs. There are various formats that could
210 | be used; one example is shown below.
211 |
212 | ```css
213 | .selector {
214 | background-image:
215 | linear-gradient(#fff, #ccc),
216 | linear-gradient(#f3c, #4ec);
217 | box-shadow:
218 | 1px 1px 1px #000,
219 | 2px 2px 1px 1px #ccc inset;
220 | }
221 | ```
222 |
223 | ### Preprocessors: additional format considerations
224 |
225 | Different CSS preprocessors have different features, functionality, and syntax.
226 | Your conventions should be extended to accommodate the particularities of any
227 | preprocessor in use. The following guidelines are in reference to Sass.
228 |
229 | * Limit nesting to 1 level deep. Reassess any nesting more than 2 levels deep.
230 | This prevents overly-specific CSS selectors.
231 | * Avoid large numbers of nested rules. Break them up when readability starts to
232 | be affected. Preference to avoid nesting that spreads over more than 20
233 | lines.
234 | * Always place `@extend` statements on the first lines of a declaration
235 | block.
236 | * Where possible, group `@include` statements at the top of a declaration
237 | block, after any `@extend` statements.
238 | * Consider prefixing custom functions with `x-` or another namespace. This
239 | helps to avoid any potential to confuse your function with a native CSS
240 | function, or to clash with functions from libraries.
241 |
242 | ```scss
243 | .selector-1 {
244 | @extend .other-rule;
245 | @include clearfix();
246 | @include box-sizing(border-box);
247 | width: x-grid-unit(1);
248 | // other declarations
249 | }
250 | ```
251 |
252 |
253 |
254 | ## 5. Practical example
255 |
256 | An example of various conventions.
257 |
258 | ```css
259 | /* ==========================================================================
260 | Grid layout
261 | ========================================================================== */
262 |
263 | /**
264 | * Column layout with horizontal scroll.
265 | *
266 | * This creates a single row of full-height, non-wrapping columns that can
267 | * be browsed horizontally within their parent.
268 | *
269 | * Example HTML:
270 | *
271 | *
272 | *
273 | *
274 | *
275 | *
276 | */
277 |
278 | /**
279 | * Grid container
280 | *
281 | * Must only contain `.cell` children.
282 | *
283 | * 1. Remove inter-cell whitespace
284 | * 2. Prevent inline-block cells wrapping
285 | */
286 |
287 | .grid {
288 | height: 100%;
289 | font-size: 0; /* 1 */
290 | white-space: nowrap; /* 2 */
291 | }
292 |
293 | /**
294 | * Grid cells
295 | *
296 | * No explicit width by default. Extend with `.cell-n` classes.
297 | *
298 | * 1. Set the inter-cell spacing
299 | * 2. Reset white-space inherited from `.grid`
300 | * 3. Reset font-size inherited from `.grid`
301 | */
302 |
303 | .cell {
304 | position: relative;
305 | display: inline-block;
306 | overflow: hidden;
307 | box-sizing: border-box;
308 | height: 100%;
309 | padding: 0 10px; /* 1 */
310 | border: 2px solid #333;
311 | vertical-align: top;
312 | white-space: normal; /* 2 */
313 | font-size: 16px; /* 3 */
314 | }
315 |
316 | /* Cell states */
317 |
318 | .cell.is-animating {
319 | background-color: #fffdec;
320 | }
321 |
322 | /* Cell dimensions
323 | ========================================================================== */
324 |
325 | .cell-1 { width: 10%; }
326 | .cell-2 { width: 20%; }
327 | .cell-3 { width: 30%; }
328 | .cell-4 { width: 40%; }
329 | .cell-5 { width: 50%; }
330 |
331 | /* Cell modifiers
332 | ========================================================================== */
333 |
334 | .cell--detail,
335 | .cell--important {
336 | border-width: 4px;
337 | }
338 | ```
339 |
340 |
341 | ## Translations
342 |
343 | * [Bahasa Indonesia](https://github.com/necolas/idiomatic-css/tree/master/translations/id-ID)
344 | * [Bulgarian](https://github.com/vestimir/idiomatic-css)
345 | * [Česky](https://github.com/necolas/idiomatic-css/tree/master/translations/cs-CZ)
346 | * [Dansk](https://github.com/necolas/idiomatic-css/tree/master/translations/da-DK)
347 | * [Deutsch](https://github.com/necolas/idiomatic-css/tree/master/translations/de-DE)
348 | * [Español](https://github.com/necolas/idiomatic-css/tree/master/translations/es-ES)
349 | * [Français](https://github.com/necolas/idiomatic-css/tree/master/translations/fr-FR)
350 | * [Italiano](https://github.com/necolas/idiomatic-css/tree/master/translations/it-IT)
351 | * [日本語](https://github.com/necolas/idiomatic-css/tree/master/translations/ja-JP)
352 | * [한국어](https://github.com/necolas/idiomatic-css/tree/master/translations/ko-KR)
353 | * [Nederlands](https://github.com/necolas/idiomatic-css/tree/master/translations/nl-NL)
354 | * [Polski](https://github.com/necolas/idiomatic-css/tree/master/translations/pl-PL)
355 | * [Português (Brasil)](https://github.com/necolas/idiomatic-css/tree/master/translations/pt-BR)
356 | * [Русский](https://github.com/necolas/idiomatic-css/tree/master/translations/ru-RU)
357 | * [Srpski](https://github.com/necolas/idiomatic-css/tree/master/translations/sr-SR)
358 | * [Türkçe](https://github.com/necolas/idiomatic-css/tree/master/translations/tr-TR)
359 | * [正體中文](https://github.com/necolas/idiomatic-css/tree/master/translations/zh-TW)
360 | * [简体中文](https://github.com/necolas/idiomatic-css/tree/master/translations/zh-CN)
361 |
362 |
363 |
364 | ## Acknowledgements
365 |
366 | Thanks to everyone who has provided translations and to all those who
367 | contributed to [idiomatic.js](https://github.com/rwldrn/idiomatic.js). It was a
368 | source of inspiration, quotations, and guidelines.
369 |
370 |
371 |
372 | ## License
373 |
374 | _Principles of writing consistent, idiomatic CSS_ by Nicolas Gallagher is
375 | licensed under the [Creative Commons Attribution 3.0 Unported
376 | License](http://creativecommons.org/licenses/by/3.0/). This applies to all
377 | documents and translations in this repository.
378 |
379 | Based on a work at
380 | [github.com/necolas/idiomatic-css](https://github.com/necolas/idiomatic-css).
381 |
--------------------------------------------------------------------------------
/translations/cs-CZ/README.md:
--------------------------------------------------------------------------------
1 | # Zásady psaní konzistentního, idiomatického CSS
2 |
3 | Tohle je příručka stylu (_style guide_) pro psaní CSS. Neberte ji jako
4 | nařizující, nechci jiným lidem vnucovat styl psaní kódu podle svých preferencí.
5 | Následující zásady ale silně podporují využívání existujících vzorů jež
6 | považuji za obvyklé a rozumné.
7 |
8 | Na dokumentu se pracuje a nové nápady vítám. Přispějte jimi prosím.
9 |
10 |
11 | [Idiomatic CSS anglicky](https://github.com/necolas/idiomatic-css/)
12 |
13 |
14 | ## Obsah
15 |
16 | 1. [Obecné principy](#general-principles)
17 | 2. [Bílá mezera](#whitespace)
18 | 3. [Komentáře](#comments)
19 | 4. [Formát](#format)
20 | 5. [Pojmenovávání](#naming)
21 | 6. [Praktická ukázka](#example)
22 | 7. [Uspořádání](#organization)
23 | 8. [Build a deploy](#build-and-deployment)
24 |
25 | [Poděkování](#acknowledgements)
26 |
27 |
28 |
29 | ## 1. Obecné principy
30 |
31 | > „Pokud chcete být dobrý správce úspěšného projektu, musíte si kromě jiného
32 | > uvědomit, že psaní kódu pro sebe je dost blbý nápad. Pokud váš kód užívají
33 | > tisíce lidí, musíte jej psát pro maximální srozumitelnost a ne pro svou
34 | > radost z dodržení specifikace.” - Idan Gazit
35 |
36 | * Nejste lidský kompiler ani kompresor kódu. Nesnažte se jím stát.
37 | * Veškerý kód jednoho projektu by měl vypadat jako by ho napsal jediný člověk.
38 | Bez ohledu na to kolik lidí přispělo.
39 | * Striktně vymáhejte dohodnutý styl.
40 | * V případě pochybností o dohodnutém stylu, použijte existující obecné vzory.
41 |
42 |
43 |
44 | ## 2. Bílá mezera
45 |
46 | V kódu vašeho projektu by měl existovat jen jediný styl užívání bílé mezery
47 | (_whitespace_). Zlepšujte s její pomocí čitelnost.
48 |
49 | * Nikdy pro odsazování nepoužívejte mezery a zároveň tabulátory.
50 | * Vyberte si buď měkké odsazení (pomocí mezer) nebo skutečné tabulátory. Držte
51 | se svého výběru bez výjimky. (Upřednostňujte mezery)
52 | * Pokud používáte mezery, zvolte si počet znaků používaných pro úroveň
53 | odsazení. (Upřednostňujte 4 mezery)
54 |
55 | Tip: nastavte si editor tak, aby zobrazoval neviditelné znaky. To vám umožní
56 | potlačit bílé mezery na konci řádků nebo nechtěné prázdné řádky s bílou
57 | mezerou. Zabráníte tak zaneřádění commitů.
58 |
59 | Tip: používejte soubor [EditorConfig](http://editorconfig.org/) (nebo něco
60 | podobného) aby vám pomohl dodržovat úmluvy o bílých mezerách, které jste
61 | dohodli pro celý projekt.
62 |
63 |
64 |
65 | ## 3. Komentáře
66 |
67 | Dobře komentovat kód je hrozně důležité. Udělejte si čas pro popis komponent,
68 | toho jak pracují, jejich omezení, a způsobu jakým jsou sestrojeny. Nenechávejte
69 | ostatní v týmu odhadovat účel neobvyklého nebo málo zřejmého kódu.
70 |
71 | Styl komentářů by měl být jednoduchý a konzistentní pro celý projekt.
72 |
73 | * Umísťujte komentáře na nový řádek nad jejich subjekt.
74 | * Vyhněte se komentářům na konci řádky.
75 | * Ponechte šířku řádky na citlivém maximu, například 80 znacích.
76 | * Velkorysým používáním komentářů dělte CSS kód do jednotlivých sekcí.
77 | * Pište komentáře ve větách (_sentence case_) a text konzistentně odsazujte.
78 |
79 | Tip: Nastavte si editor tak, abyste dohodnuté komentářové vzory měli vždy po
80 | ruce.
81 |
82 | #### Example:
83 |
84 | ```css
85 | /* ==========================================================================
86 | Nadpis pro sekci
87 | ========================================================================== */
88 |
89 | /* Nadpis pro podsekci
90 | ========================================================================== */
91 |
92 | /**
93 | * Kratky popis co se drzi komentaroveho formatu Doxygen
94 | *
95 | * Tady zacina prvni veta dlouheho popisu a chvili pokracuje dokud neskonci
96 | * na dalsim radku.
97 | *
98 | * Nejdelsi popisek je idealni pro detailnejsi vysvetleni a dokumentace. Muze
99 | * obsahovat ukazkove HTML, URL adresy nebo jakekoliv jine informace co se
100 | * povazuji za nezbytne nebo uzitecne.
101 | *
102 | * @tag Tohle je znacka s nazvem „tag”
103 | *
104 | * @todo Tohle je popis ukolu (todo) co ma byt vyresen pozdeji.
105 | * Zalomi se po 80ti znacich. Druhy a dalsi radky odsazujeme 2 mezerami.
106 | */
107 |
108 | /* Jednoduchy komentar */
109 | ```
110 |
111 | _(Pozn. překl. – Komentáře v kódu je lepší jednotně psát bez diakritiky. Hlavně
112 | proto, že velká část českých vývojářů píše kód pomocí anglické klávesnice.)_
113 |
114 |
115 |
116 | ## 4. Formát
117 |
118 | Zvolený formát musí zajistit aby číst kód a vytvářet v něm srozumitelné
119 | komentáře bylo snadné. Omezte riziko náhodně vzniklých chyb. Výsledkem dobrého
120 | a jednotného formátu je snadné porovnávání dvou verzí (_diff_) a čitelný
121 | _blame_, jež ukazuje autora a commit poslední změny konkrétního řádku.
122 |
123 | * V pravidlech obsahujících více selektorů mějte každý selektor na
124 | samostatné řádce.
125 | * Před otevírací složenou závorku pravidla vkládejte jednu mezeru.
126 | * V bloku deklarací mějte každou deklaraci na zvláštním řádku.
127 | * Každou deklaraci odsazujte o jednu úroveň.
128 | * V deklaraci pište za dvojtečku jednu mezeru.
129 | * Ve zkrácených variantách hexa hodnot barev používejte malá písmena
130 | (např. `#aaa`).
131 | * Konzistentně používejte jednoduché anebo dvojité „uvozovky”.
132 | Doporučujeme dvojité (např. `content: ""`).
133 | * Hodnoty atribut selektorů uvádějte v „uvozovkách” (např.
134 | `input[type="checkbox"]`).
135 | * Tam kde je to u nulových hodnot možné, vyhněte se uvádění jednotek
136 | (např. `margin: 0`).
137 | * Za každou čárku použitou jako oddělovač hodnot nebo parametrů funkcí
138 | vložte mezeru.
139 | * Na konec každé deklarace v bloku deklarací vložte středník.
140 | * Uzavírací složenou závorku pro konec pravidla odsaďte stejně jako první
141 | znak pravidla.
142 | * Jednotlivá pravidla oddělujte prázdným řádkem.
143 |
144 | ```css
145 | .selector-1,
146 | .selector-2,
147 | .selector-3[type="text"] {
148 | -webkit-box-sizing: border-box;
149 | -moz-box-sizing: border-box;
150 | box-sizing: border-box;
151 | display: block;
152 | font-family: helvetica, arial, sans-serif;
153 | color: #333;
154 | background: #fff;
155 | background: linear-gradient(#fff, rgba(0, 0, 0, 0.8));
156 | }
157 | ```
158 |
159 | #### Pořadí deklarací
160 |
161 | Deklarace v kódu jednoho projektu řaďte v souladu s jediným principem.
162 | Upřednostňuji deklarovat nejprve konstrukčně důležité vlastnosti (např.
163 | pozicování nebo box model).
164 |
165 | ```css
166 | .selector {
167 | /* Pozicovani */
168 | position: absolute;
169 | z-index: 10;
170 | top: 0;
171 | right: 0;
172 | bottom: 0;
173 | left: 0;
174 |
175 | /* Zobrazeni & box model */
176 | display: inline-block;
177 | overflow: hidden;
178 | box-sizing: border-box;
179 | width: 100px;
180 | height: 100px;
181 | padding: 10px;
182 | border: 10px solid #333;
183 | margin: 10px;
184 |
185 | /* Ostatni */
186 | background: #000;
187 | color: #fff
188 | font-family: sans-serif;
189 | font-size: 16px;
190 | text-align: right;
191 | }
192 | ```
193 |
194 | Poměrně populární je také abecední pořadí. To má ale nevýhodu, že odděluje
195 | příbuzné vlastnosti. Například – ofsety pozice (vlastnosti `top`, `left` apod.)
196 | tak nemohou být seskupeny dohromady a vlastnosti box-modelu mohou skončit
197 | rozptýlené po celém pravidle.
198 |
199 | _(Pozn. překl. — Některé vlastnosti jsou navíc pro rychlý sken stylopisu
200 | důležitější než jiné – position, z-index. I proto jim patří místo na začátku
201 | pravidla.)_
202 |
203 | #### Výjimky a mírné odchylky
204 |
205 | Velké bloky pravidel s jednou deklarací můžete zapisovat trochu jinak — na
206 | jeden řádek. V tomto případě by za otevírací a před uzavírací složenou závorkou
207 | neměla chybět mezera.
208 |
209 | ```css
210 | .selector-1 { width: 10%; }
211 | .selector-2 { width: 20%; }
212 | .selector-3 { width: 30%; }
213 | ```
214 |
215 | Dlouhé bloky hodnot oddělované čárkou – jako třeba vícenásobná pozadí nebo
216 | stíny – je lepší pro zlepšení čitelnosti nebo zajištění užitečnějších diffů
217 | rozdělit do více řádků. Formátů jež je možné použít je mnoho. Tady je jeden
218 | příklad:
219 |
220 | ```css
221 | .selector {
222 | background-image:
223 | linear-gradient(#fff, #ccc),
224 | linear-gradient(#f3c, #4ec);
225 | box-shadow:
226 | 1px 1px 1px #000,
227 | 2px 2px 1px 1px #ccc inset;
228 | }
229 | ```
230 |
231 | ### Preprocesory
232 |
233 | Různé CSS preprocesory mají různé vlastnosti, funkce a syntaxi. Vaše konvence
234 | byste měli rozšířit tak, aby vyhověly zvláštnostem preprocesoru, který
235 | využíváte. Následující zásady se vztahují k Sass.
236 |
237 | * Omezte zanořování pravidel na 1 úroveň. Přehodnoťte každé zanořování
238 | hlubší než 2 úrovně. To omezí existenci příliš specifických selektorů.
239 | * Vyhněte se velkému množství vnořených pravidel. Jakmile se čitelnost
240 | začíná zhoršovat, rozdělte je. Doporučuji rozdělovat vnořená pravidla
241 | jež zaberou více než 20 řádků.
242 | * Direktivy `@extend` vždy zapisujte do prvních řádků pravidla.
243 | * Tam kde je to možné seskupte direktivy `@include` hned za řádky s `@extend`.
244 | * Zvažte prefixování vašich funkcí pomocí x- nebo jiného jmenného prostoru.
245 | To vám pomůže vyhnout se kolizím s názvy nativních CSS funkcí nebo funkcí
246 | z knihoven.
247 |
248 | ```scss
249 | .selector-1 {
250 | @extend .other-rule;
251 | @include clearfix();
252 | @include box-sizing(border-box);
253 | width: x-grid-unit(1);
254 | // ostatni deklarace
255 | }
256 | ```
257 |
258 |
259 |
260 | ## 5. Pojmenovávání
261 |
262 | Pojmenovávání je těžké, ale velice důležité. Je to stěžejní část procesu vývoje
263 | spravovatelného kódu. Dobrý způsob pojmenovávání vám zajistí škálovatelné
264 | rozhraní mezi vaším HTML a CSS.
265 |
266 | * Vyhněte se systematickému používání zkrácených názvů tříd. Nedělejte
267 | věci těžké k pochopení.
268 | * Pro třídy v HTML používejte čisté, smysluplné a odpovídající názvy.
269 | * Vyberte srozumitelný a konzistentní vzorec pojmenovávání co dává smysl jak
270 | v HTML tak CSS souborech.
271 | * Selektory pro komponenty by měly využívat názvy tříd. Vyhněte se
272 | používání generických značek (tagů) nebo unikátních id.
273 |
274 | ```css
275 | /* Ukazky kodu se spatnymi pojmenovavanim selektoru */
276 |
277 | .s-scr {
278 | overflow: auto;
279 | }
280 |
281 | .cb {
282 | background: #000;
283 | }
284 |
285 | /* Ukazky kodu s lepsim pojmenovanim selektoru */
286 |
287 | .is-scrollable {
288 | overflow: auto;
289 | }
290 |
291 | .column-body {
292 | background: #000;
293 | }
294 | ```
295 |
296 |
297 |
298 | ## 6. Praktická ukázka
299 |
300 | ```css
301 | /* ==========================================================================
302 | Mrizkovy layout
303 | ========================================================================== */
304 |
305 | /**
306 | * Ukazka HTML:
307 | *
308 | *
312 | */
313 |
314 | .grid {
315 | overflow: visible;
316 | height: 100%;
317 | /* Zamezi zalomeni inline-block bunek mrizky */
318 | white-space: nowrap;
319 | /* Odstrani mezeru mezi bunkami */
320 | font-size: 0;
321 | }
322 |
323 | .cell {
324 | position: relative;
325 | display: inline-block;
326 | overflow: hidden;
327 | box-sizing: border-box;
328 | width: 20%;
329 | height: 100%;
330 | /* Nastavime vnitrni okraj bunek */
331 | padding: 0 10px;
332 | border: 2px solid #333;
333 | vertical-align: top;
334 | /* Resetujeme bilou mezeru */
335 | white-space: normal;
336 | /* Resetujeme velikost pisma */
337 | font-size: 16px;
338 | }
339 |
340 | /* Stavy bunky */
341 |
342 | .cell.is-animating {
343 | background-color: #fffdec;
344 | }
345 |
346 | /* Varianty sirky bunky
347 | ========================================================================== */
348 |
349 | .cell-1 { width: 10%; }
350 | .cell-2 { width: 20%; }
351 | .cell-3 { width: 30%; }
352 | .cell-4 { width: 40%; }
353 | .cell-5 { width: 50%; }
354 |
355 | /* Modifikatory bunky
356 | ========================================================================== */
357 |
358 | .cell--detail,
359 | .cell--important {
360 | border-width: 4px;
361 | }
362 | ```
363 |
364 |
365 |
366 | ## 7. Uspořádání
367 |
368 | Uspořádání (organizace větších celků) je důležitá vlastnost každé CSS části
369 | kódu projektu, ale pro ty větší je dost zásadní.
370 |
371 | * Logicky oddělujte odlišné části kódu.
372 | * Pro odlišné komponenty kódu používejte oddělené soubory, které pak spojte
373 | v sestavovacím (_build_) kroku.
374 | * Pokud používáte preprocesor, zobecněte často používaný kód do proměnných
375 | pro barvy, typografii atd.
376 |
377 |
378 |
379 | ## 8. Build a deploy
380 |
381 | Určitě byste se měli pokusit na projektu nasadit nějaké nástroje pomocí kterých
382 | můžete kód projektu prověřit lint analýzou, zkomprimovat a verzovat během
383 | přípravy pro produkční použití. Pro tenhle účel existuje vynikající nástroj
384 | [grunt](https://github.com/cowboy/grunt) od Bena Almana.
385 |
386 |
387 |
388 | ## Poděkování
389 |
390 | Díky všem co přispěli k [idiomatic.js](https://github.com/rwldrn/idiomatic.js).
391 | Byl to můj zdroj inspirace, citací a zásad.
392 |
--------------------------------------------------------------------------------
/translations/da-DK/README.md:
--------------------------------------------------------------------------------
1 | # Principper for at skrive konsistent, idiomatisk CSS
2 |
3 | Dette dokument skitserer en række fornuftige og logiske retningslinjer til CSS udvikling.
4 | Det er ikke ment som et asolut regelsæt og jeg ønsker ikke at presse min måde at
5 | skrive CSS på ned over andres kode. Ikke desto mindre så indbyder disse principper
6 | til at benytte allerede eksisterende og logiske kodemønstre.
7 |
8 | Dette dokument er levende og nye tilføjelser og idéer er altid velkomne.
9 |
10 |
11 | ## Oversættelser
12 |
13 | * [Dansk](https://github.com/necolas/idiomatic-css/tree/master/translations/da-DK)
14 | * [Italiano](https://github.com/necolas/idiomatic-css/tree/master/translations/it-IT)
15 | * [日本語](https://github.com/necolas/idiomatic-css/tree/master/translations/ja-JP)
16 | * [Nederlands](https://github.com/necolas/idiomatic-css/tree/master/translations/nl-NL)
17 | * [Português (Brasil)](https://github.com/necolas/idiomatic-css/tree/master/translations/pt-BR)
18 | * [Srpski](https://github.com/necolas/idiomatic-css/tree/master/translations/sr)
19 | * [Türkçe](https://github.com/necolas/idiomatic-css/tree/master/translations/tr-TR)
20 | * [简体中文](https://github.com/necolas/idiomatic-css/tree/master/translations/zh-CN)
21 |
22 |
23 | ## Indholdsfortegnelse
24 |
25 | 1. [Generelle principper](#general-principles)
26 | 2. [Mellemrum](#whitespace)
27 | 3. [Kommentarer](#comments)
28 | 4. [Formatering](#format)
29 | 5. [Navngivning](#naming)
30 | 6. [Praktisk eksempel](#example)
31 | 7. [Organisering](#organization)
32 | 8. [Build og udrulning](#build-and-deployment)
33 |
34 | [Anerkendelser](#acknowledgements)
35 |
36 |
37 |
38 | ## 1. Generelle principper
39 |
40 | > "En del af det at være en god forvalter af et succésfuldt projekt er at
41 | > indse, at det at skrive kode til én selv er En Dårlig Idé™. Hvis tusindvis af
42 | > mennesker bruger din kode, bør du optimere din kode til maksimal
43 | > læsevenlighed, ikke til dine personlige preferencer og sjove eller underlige
44 | > forkortelser." - Idan Gazit
45 |
46 | * Al kode i kode-basen bør se ud som om, kun én person har skrevet det hele,
47 | uanset hvor mange der rent faktisk har leveret indhold.
48 | * Håndhæv den aftalte stil strengt.
49 | * Hvis der er tvivl bør eksisterende, bredt accepterede kodemønstre benyttes.
50 |
51 |
52 |
53 | ## 2. Mellemrum
54 |
55 | Kun én stil bør eksistere på tværs af hele dit projekts kilde. Vær altid
56 | konsistent i din brug af mellemrum. Brug mellemrum og ekstra linjeskift til at
57 | forbedre læsbarheden.
58 |
59 | * Du må _aldrig_ blande mellemrum og tablatorer ved indrykning.
60 | * Vælg mellem bløde indrykninger (mellemrum) eller tabulatorer. Stå ved dit
61 | valg uden forbehold. (Anbefales: mellemrum)
62 | * Hvis du bruger mellemrum, vælges et antal der bruges pr. indrykningsniveau.
63 | (Anbefales: 4 mellemrum)
64 |
65 | Tip: Indstil din CSS-editor til at vise skjulte tegn. Dette giver dig mulighed
66 | for, at slette mellemrum i slutningen af kodelinjer, slette uønskede
67 | dobbelt-mellemrum og dermed undgå at "forurene" kode-commits.
68 |
69 |
70 |
71 | ## 3. Kommentarer
72 |
73 | Velkommenteret (og dermed veldokumenteret) kode er virkelig vigtigt. Brug tid
74 | på at beskrive komponenter, hvordan de virker, deres begrænsninger og måden
75 | hvorpå de er konstrueret. Overlad det ikke til andre i teamet at gætte sig frem
76 | til, hvad usædvanlig eller ikke-indlysende kode skal bruges til.
77 |
78 | Kommentar-stilen bør være simpel og konsistent på tværs er hele kode-basen.
79 |
80 | * Placér kommentarer på en ny linje over den kode, de beskriver.
81 | * Undgå kommentarer for enden af kodelinjer.
82 | * Hold kommentarlinjer fornuftigt korte, fx 80 karakterer.
83 | * Vær gavmild med kommentarer til at bryde CSS'en op i mindre sektioner.
84 | * Brug korrekt grammetik i kommentarer og vær konsistent med tekst-indrykning.
85 |
86 | Tip: Indstil din CSS-editor til at give dig genveje til at indsætte
87 | tekststumper med de aftalte kommentar-mønstre.
88 |
89 | #### CSS-eksempel:
90 |
91 | ```css
92 | /* ==========================================================================
93 | Afsnit kommentar-blok
94 | ========================================================================== */
95 |
96 | /* Underafsnit kommentar-blok
97 | ========================================================================== */
98 |
99 | /*
100 | * Gruppe kommentar-blok.
101 | * Idéel til fler-linjede forklaringer og dokumentation.
102 | */
103 |
104 | /* Simpel kommentar */
105 | ```
106 |
107 | #### SCSS-eksempel:
108 |
109 | ```scss
110 | // ==========================================================================
111 | // Afsnit kommentar-blok
112 | // ==========================================================================
113 |
114 | // Underafsnit kommentar-blok
115 | // ==========================================================================
116 |
117 | //
118 | // Gruppe kommentar-blok.
119 | // Idéel til fler-linjede forklaringer og dokumentation.
120 | //
121 |
122 | // Simpel kommentar
123 | ```
124 |
125 |
126 |
127 | ## 4. Formatering
128 |
129 | Det valgte kodeformat skal tilsikre at koden er: nem at læse; nem at kommentere
130 | klart; minimere risikoen for at introducere fejl ved et tilfælde; og resulterer
131 | i brugbare diffs og blames
132 | (https://git.wiki.kernel.org/index.php/Textconv#Blame_and_diff)
133 |
134 | 1. Én diskret selector pr. linje i multi-selector regelsæt.
135 | 2. Ét enkelt mellemrum før krøllet start-parentes i regelsæt.
136 | 3. Én erklæring pr. linje i regelsæt.
137 | 4. Ét indrykningsniveau på regelsæt.
138 | 5. Ét enkelt mellemrum efter kolon i hver erklæring.
139 | 6. Afslut _alle_ erklæringer med et semikolon - også den sidste.
140 | 7. Placér den krøllede slut-parentes på samme indrykningsniveau som det første
141 | tegn i regelsættet.
142 | 8. Opdel de enkelte regelsæt med en tom linje.
143 |
144 | ```css
145 | .selector-1,
146 | .selector-2,
147 | .selector-3 {
148 | -webkit-box-sizing: border-box;
149 | -moz-box-sizing: border-box;
150 | box-sizing: border-box;
151 | display: block;
152 | color: #333;
153 | background: #fff;
154 | }
155 | ```
156 |
157 | #### Erklæringers rækkefølge
158 |
159 | Erklæringer bør sorteres i overensstemmelse med et simpelt princip. Mit
160 | foretrukne princip er at gruppere relaterede egenskaber sammen, og
161 | strukturmæssigt vigtigt egenskaber (fx positionering og box-modellen) erklæring
162 | inden typografi, baggrund og farveegenskaber.
163 |
164 | ```css
165 | .selector {
166 | position: relative;
167 | display: block;
168 | width: 50%;
169 | height: 100px;
170 | padding: 10px;
171 | border: 0;
172 | margin: 10px;
173 | color: #fff
174 | background: #000;
175 | }
176 | ```
177 |
178 | Alfabetisk rækkefølge er også populær, men ulempen er, at denne sortering
179 | adskiller relaterede egenskaber. For eksempel vil positioneringsegenskaber ikke
180 | længere være samlet i en gruppe, og box-modellens egenskaber kan ende med at
181 | blive spredt ud over hele regelsættet.
182 |
183 | #### Undtagelser og små afvigelser
184 |
185 | Store blokke af enkelt-linje erklæringer kan benytte et enkeltlinje-format. I
186 | dette tilfælde bør der inkluderes et enkelt mellemrum før krøllet
187 | start-parentes og inden krøllet slut-parentes.
188 |
189 | ```css
190 | .selector-1 { width: 10%; }
191 | .selector-2 { width: 20%; }
192 | .selector-3 { width: 30%; }
193 | ```
194 |
195 | Lange, kommaseparerede egenskaber - fx samlinger af farveforløb eller skygger -
196 | kan arrangeres over flere linjer, i en betræbelse på, at forbedre læsbarheden
197 | og producere mere brugbare diffs. Det er flere forskellige formater der kan
198 | benyttes; en måde at gøre det på kan ses herunder.
199 |
200 | ```css
201 | .selector {
202 | box-shadow:
203 | 1px 1px 1px #000,
204 | 2px 2px 1px 1px #ccc inset;
205 | background-image:
206 | linear-gradient(#fff, #ccc),
207 | linear-gradient(#f3c, #4ec);
208 | }
209 | ```
210 |
211 | #### Diverse
212 |
213 | * Brug små bogstaver i hex værdier, fx `#aaa`.
214 | * Brug enkelt- eller dobbelt-anførselstegn konsistent. Dobbelt-anførselstegn
215 | foretrækkes, fx `content: ""`.
216 | * Brug altid anførselstegn i selctorers egenskaber, fx
217 | `input[type="checkout"]`.
218 | * _Hvor det er muligt_ bør du undgå at specificere enheder for nul-værdier, fx
219 | `margin: 0`.
220 |
221 | ### Preprocessors: Ekstra overvejelser i forbindelse med formatering
222 |
223 | Forskellige CSS preprocessors har forskellige egenskaber, funktionalitet og
224 | syntaks. Dine konventioner bør udvides og tilpasses, således at de imødekommer
225 | de forhold, der er i de proprocessors der benyttes af gruppen. De efterfølgende
226 | guidelines relaterer sig til SASS.
227 |
228 | * Begræns indlejring til 1 niveau. Genovervej alle indlejringer der er mere end
229 | 2 niveauer dyb. Dette forhindrer alt for specifikke CSS selektorer.
230 | * Undgå et højt antal indlejrede regler. Bryd dem op når læsbarheden begynder
231 | at blive påvirket. Det anbefales at undgå indlejringer der breder sig over
232 | mere end 20 linjer.
233 | * Placér altid `@extend`-erklæringer på første linje i regelsæt.
234 | * Hvis det er muligt, placeres `@include` i toppen af regelsættet, lige efter
235 | `@extend`-erklæringer.
236 | * Overvej at starte brugerdeficerede funktioner med `x-` eller lignende. Dette
237 | hjælper med at undgå, at dine funktioner konflikter med (eller overskriver)
238 | standard CSS-funktioner fra biblioteker og frameworks.
239 |
240 | ```scss
241 | .selector-1 {
242 | @extend .other-rule;
243 | @include clearfix();
244 | @include box-sizing(border-box);
245 | width: x-grid-unit(1);
246 | // andre erklæringer
247 | }
248 | ```
249 |
250 |
251 |
252 | ## 5. Navngivning
253 |
254 | Du er ikke en menneskelig compiler/compressor, så lad være med at prøve at være
255 | en sådan.
256 |
257 | Brug klare og logiske navne til dine HTML-class'er. Vælg et forståelig og
258 | konstistent navngivningsmønster der giver mening i både HTML- og CSS-filer.
259 |
260 | ```css
261 | /* Eksempel på kode med dårlig navngivning */
262 |
263 | .s-scr {
264 | overflow: auto;
265 | }
266 |
267 | .cb {
268 | background: #000;
269 | }
270 |
271 | /* Eksempel på kode med god navngivning */
272 |
273 | .is-scrollable {
274 | overflow: auto;
275 | }
276 |
277 | .column-body {
278 | background: #000;
279 | }
280 | ```
281 |
282 |
283 |
284 | ## 6. Praktisk eksempel
285 |
286 | Et eksempel på en række forskellige konventioner.
287 |
288 | ```css
289 | /* ==========================================================================
290 | Gitter layout
291 | ========================================================================== */
292 |
293 | /*
294 | * HTML-eksempel:
295 | *
296 | *
300 | */
301 |
302 | .grid {
303 | overflow: visible;
304 | height: 100%;
305 | /* Undgå at "inline-block"-celler ombrydes */
306 | white-space: nowrap;
307 | /* Fjerner mellemrum mellem celler */
308 | font-size: 0;
309 | }
310 |
311 | .cell {
312 | box-sizing: border-box;
313 | position: relative;
314 | overflow: hidden;
315 | width: 20%;
316 | height: 100%;
317 | /* Angiver mellemrum mellem celler */
318 | padding: 0 10px;
319 | border: 2px solid #333;
320 | vertical-align: top;
321 | /* Nulstil white-space */
322 | white-space: normal;
323 | /* Nulstil font-size */
324 | font-size: 16px;
325 | }
326 |
327 | /* Cellers tilstande */
328 |
329 | .cell.is-animating {
330 | background-color: #fffdec;
331 | }
332 |
333 | /* Cellers dimensioner
334 | ========================================================================== */
335 |
336 | .cell-1 { width: 10%; }
337 | .cell-2 { width: 20%; }
338 | .cell-3 { width: 30%; }
339 | .cell-4 { width: 40%; }
340 | .cell-5 { width: 50%; }
341 |
342 | /* Celle-ændringer
343 | ========================================================================== */
344 |
345 | .cell--detail,
346 | .cell--important {
347 | border-width: 4px;
348 | }
349 | ```
350 |
351 |
352 |
353 | ## 7. Organisering
354 |
355 | Organisering af kode er en vigtig del af enhver CSS kodebase, og livsnødvendig
356 | for store kodebaser.
357 |
358 | * Lav en logisk separering mellem særskilte stumper af kode.
359 | * Brug separate filer (sammenkædes i et build) for at bryde koden op i
360 | særskilte komponenter.
361 | * Hvis du bruger en preprocessor, opsættes fælles kode i variabler for farver,
362 | typografi osv.
363 |
364 |
365 | ## 8. Builds og udrulning
366 |
367 | Forud for brug i live-miljøer, bør projekter altid forsøge at inkludere en
368 | generisk metode til at linte, teste, komprimere og versionere koden. Til dette
369 | formål er [grunt](https://github.com/cowboy/grunt) af Ben Alman et fremragende
370 | værktøj.
371 |
372 |
373 |
374 | ## Anerkendelser
375 |
376 | Tak til alle der har bidraget til
377 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js). I har været en
378 | fantastisk kilde til inspiration, noteringer og retningslinjer.
379 |
--------------------------------------------------------------------------------
/translations/de-DE/README.md:
--------------------------------------------------------------------------------
1 | # Grundlagen zum Schreiben von einheitlichem, idiomatischem CSS
2 |
3 | Das folgende Dokument legt eine vernünftige Gestaltungsrichtlinie für die
4 | CSS-Entwicklung dar. Diese Richtlinien ermutigen zur Verwendung existierender,
5 | üblicher und sinnvoller Muster. Sie sollten nach Bedarf angepasst werden, um
6 | eine eigene Gestaltungsrichtlinie zu erstellen.
7 |
8 | Dies ist ein lebendiges Dokument, und neue Ideen sind immer willkommen. Bitte
9 | trage bei.
10 |
11 | [Idiomatic CSS auf englisch](https://github.com/necolas/idiomatic-css/).
12 |
13 |
14 | ## Inhaltsverzeichnis
15 |
16 | 1. [Allgemeine Grundlagen](#general-principles)
17 | 2. [Leerraum](#whitespace)
18 | 3. [Kommentare](#comments)
19 | 4. [Formatierung](#format)
20 | 5. [Praktisches Beispiel](#example)
21 |
22 | [Danksagung](#acknowledgements)
23 |
24 | [Lizenz](#license)
25 |
26 |
27 |
28 | ## 1. Allgemeine Grundlagen
29 |
30 | > „Ein Teil der Aufgabe eines guten Verwalters eines erfolgreichen Projekts ist
31 | > es, zu realisieren, dass Code für sich selbst zu schreiben eine schlechte
32 | > Idee™ ist. Wenn tausende Leute deinen Code verwenden, dann schreibe deinen
33 | > Code für maximale Klarheit, nicht nach deinen persönlichen Vorlieben, wie
34 | > man innerhalb der Spezifikation gerissen sein kann.“ - Idan Gazit
35 |
36 | * Du bist kein menschlicher Code-Compiler/Kompressor, versuche also nicht,
37 | einer zu sein.
38 | * Der gesamte Code in jeder Code-Basis soll aussehen wie von einer einzigen
39 | Person eingegeben, unabhängig davon wieviele Leute beigetragen haben.
40 | * Erzwinge den vereinbarten Stil streng.
41 | * Im Zweifel bei einer Stilentscheidung verwende bestehende, übliche Muster.
42 |
43 |
44 |
45 | ## 2. Leerraum
46 |
47 | Nur ein Stil soll in den gesamten Quellen deines Projekts existieren. Sei
48 | stets konsistent beim Einsatz von Leerraum. Verwende Leerraum, um die
49 | Lesbarkeit zu erhöhen.
50 |
51 | * Mische _niemals_ Leerzeichen und Tabs zur Einrückung.
52 | * Wähle zwischen weicher Einrückung (Leerzeichen) oder wirklichen Tabs. Bleibe
53 | bei deiner Wahl ohne Abweichung. (Vorzug: Leerzeichen)
54 | * Beim Einsatz von Leerzeichen wähle die Anzahl Zeichen pro Einrückebene.
55 | (Vorzug: 4 Leerzeichen)
56 |
57 | Tipp: Richte deinen Editor so ein, dass er unsichtbare Zeichen zeigt. Das
58 | erlaubt dir, Leerzeichen am Zeilenende zu entfernen, unbeabsichtigte
59 | Leerzeichen in leeren Zeilen und Commits zu verschmutzen.
60 |
61 | Tipp: Verwende eine [EditorConfig](http://editorconfig.org/)-Datei (oder
62 | entsprechend), um die grundlegenden Leerraum-Konventionen, die vereinbart
63 | wurden, verwalten zu helfen.
64 |
65 |
66 |
67 | ## 3. Kommentare
68 |
69 | Gut kommentierter Code ist extrem wichtig. Nimm dir Zeit, Komponenten zu
70 | beschreiben, wie sie arbeiten, welche Beschränkungen sie haben und wie sie
71 | gebaut sind. Lass andere im Team nicht raten, was den Zweck von ungewöhnlichem
72 | oder nicht offensichtlichem Code betrifft.
73 |
74 | Der Kommentarstil soll einfach und konsistent innerhalb einer einzelnen
75 | Code-Basis sein.
76 |
77 | * Platziere Kommentare auf neuen Zeilen über ihrem Gegenstand.
78 | * Behalte die Zeilenlänge bei einem sinnvollen Maximum, z.B. 80 Spalten.
79 | * Mache großzügigen Gebrauch von Kommentaren, um CSS in einzelne Abschnitte zu
80 | unterteilen.
81 | * Beginne mit einem Großbuchstaben und verwende konsistente Einrückung.
82 |
83 | Tip: Konfiguriere deinen Editor so, dass er Kürzel für die Ausgabe von
84 | ausgemachten Kommentar-Mustern anbietet.
85 |
86 | Beispiel:
87 |
88 | ```css
89 | /* ==========================================================================
90 | Abschnitt Kommentar-Block
91 | ========================================================================== */
92 |
93 | /* Unterabschnitt Kommentar-Block
94 | ========================================================================== */
95 |
96 | /**
97 | * Kurze Beschreibung im Doxygen-Stilformat
98 | *
99 | * Der erste Satz der langen Beschreibung beginnt hier und wird auf dieser
100 | * Zeile für eine Weile fortgeführt, bis er schließlich hier endet.
101 | *
102 | * Die lange Beschreibung ist ideal für detailliertere Erläuterungen und
103 | * Dokumentation. Sie kann Beispiel-HTML, URLs und andere Information
104 | * beinhalten, die nützlich oder notwendig erscheint.
105 | *
106 | * @tag Dies ist ein Schlagwort namens 'tag'
107 | *
108 | * @todo Dies ist eine Todo-Angabe, die eine unteilbare Aufgabe beschreibt,
109 | * die später vollendet wird. Sie bricht nach 80 Zeichen um und folgende
110 | * Zeilen sind mit zwei Leerzeichen eingerückt.
111 | */
112 |
113 | /* Einfacher Kommentar */
114 | ```
115 |
116 |
117 |
118 | ## 4. Formatierung
119 |
120 | Die gewählte Codeformatierung muss gewährleisten, dass der Code: leicht zu
121 | lesen ist; leicht klar zu kommentieren ist; nicht dazu verleitet, unabsichtlich
122 | Fehler einzuführen; und zu nützlichen Diffs und Blames der Versionsverwaltung
123 | führt.
124 |
125 | * Verwende einen einzelnen Selektor pro Zeile in Multi-Selektor-Regelsets.
126 | * Füge ein einzelnes Leerzeichen vor der öffnenden Klammer eines Regelsets ein.
127 | * Füge eine Deklaration pro Zeile in einem Deklarationsblock ein.
128 | * Verwende eine Einrückungsebene für jede Deklaration.
129 | * Füge ein einzelnes Leerzeichen nach dem Doppelpunkt jeder Deklaration ein.
130 | * Verwende Kleinbuchstaben und Kurzschreibweise bei Hexwerten, z. B. `#aaa`.
131 | * Verwende einfache oder doppelte Anführungszeichen konsistent. Doppelte
132 | Anführungszeichen werden bevorzugt, z. B. `content: ""`.
133 | * Setze Attributwerte in Selektoren in Anführungszeichen, z. B.
134 | `input[type="checkbox"]`.
135 | * _Wo es erlaubt ist,_ vermeide die Angabe von Einheiten für Nullwerte, z. B.
136 | `margin: 0`.
137 | * Füge ein Leerzeichen nach jedem Komma ein bei komma-getrennten Eigenschaften
138 | oder Funktionswerten.
139 | * Füge einen Strichpunkt nach der letzten Deklaration in einem
140 | Deklarationsblock ein.
141 | * Platziere die schließende Klammer eines Regelsets in derselben Spalte wie
142 | das erste Zeichen des Regelsets.
143 | * Trenne jedes Regelset mit einer Leerzeile.
144 |
145 | ```css
146 | .selektor-1,
147 | .selektor-2,
148 | .selektor-3[type="text"] {
149 | -webkit-box-sizing: border-box;
150 | -moz-box-sizing: border-box;
151 | box-sizing: border-box;
152 | display: block;
153 | font-family: helvetica, arial, sans-serif;
154 | color: #333;
155 | background: #fff;
156 | background: linear-gradient(#fff, #bbb);
157 | background: linear-gradient(#fff, rgba(0, 0, 0, 0.8));
158 | }
159 |
160 | .selektor-a,
161 | .selektor-b {
162 | padding: 10px;
163 | }
164 | ```
165 |
166 | #### Deklarations-Reihenfolge
167 |
168 | Deklarationen sollen nach einem einzelnen, einfachen Prinzip sortiert werden,
169 | wenn sie geordnet werden. Ich bevorzuge es, strukturell wichtige Eigenschaften
170 | (z.B. Positionierung und Box-Modell) vor allen anderen zu notieren.
171 |
172 | ```css
173 | .selektor {
174 | /* Positionierung */
175 | position: absolute;
176 | z-index: 10;
177 | top: 0;
178 | right: 0;
179 | bottom: 0;
180 | left: 0;
181 |
182 | /* Anzeige & Box-Modell */
183 | display: inline-block;
184 | overflow: hidden;
185 | box-sizing: border-box;
186 | width: 100px;
187 | height: 100px;
188 | padding: 10px;
189 | border: 10px solid #333;
190 | margin: 10px;
191 |
192 | /* Andere */
193 | background: #000;
194 | color: #fff;
195 | font-family: sans-serif;
196 | font-size: 16px;
197 | text-align: right;
198 | }
199 | ```
200 |
201 | Streng alphabetische Sortierung ist ebenfalls populär, hat aber den Nachteil,
202 | dass sie verwandte Eigenschaften trennt. Zum Beispiel sind Positions-Versätze
203 | nicht mehr zusammen gruppiert und Box-Modell-Eigenschaften können sich über
204 | einen ganzen Deklarationsblock verteilt wiederfinden.
205 |
206 | #### Ausnahmen und leichte Abweichungen
207 |
208 | Große Blöcke mit einzelnen Deklarationen können ein leicht unterschiedliches,
209 | einzeiliges Format verwenden. In diesem Fall wird ein Leerzeichen nach der
210 | öffnenden und vor der schließenden Klammer eingefügt.
211 |
212 | ```css
213 | .selektor-1 { width: 10%; }
214 | .selektor-2 { width: 20%; }
215 | .selektor-3 { width: 30%; }
216 | ```
217 |
218 | Lange, komma-getrennte Eigenschaftswerte - wie Sammlungen von Gradienten oder
219 | Schatten - können über mehrere Zeilen angeordnet werden, um die Lesbarkeit zu
220 | erhöhen und nützlichere Diffs zu produzieren. Es gibt verschiedene
221 | Formatierungen, die verwendet werden können; ein Beispiel ist im Folgenden
222 | gezeigt.
223 |
224 | ```css
225 | .selektor {
226 | background-image:
227 | linear-gradient(#fff, #ccc),
228 | linear-gradient(#f3c, #4ec);
229 | box-shadow:
230 | 1px 1px 1px #000,
231 | 2px 2px 1px 1px #ccc inset;
232 | }
233 | ```
234 |
235 | ### Präprozessoren: Zusätzliche Formatier-Überlegungen
236 |
237 | Verschiedene CSS-Präprozessoren haben verschiedene Besonderheiten,
238 | Funktionalität und Syntax. Deine Konventionen sollen so erweitert werden, dass
239 | sie den Eigenheiten jedes verwendeten Präprozessors Rechnung tragen. Die
240 | folgenden Richtlinien beziehen sich auf Sass.
241 |
242 | * Beschränke Verschachtelungen auf eine Ebene Tiefe. Überprüfe jede
243 | Verschachtelung tiefer als 2 Ebenen. Das verhindert übermäßg spezifische
244 | CSS-Selektoren.
245 | * Vermeide große Mengen verschachtelter Regeln. Brich sie in Teile auf, wenn
246 | Lesbarkeit beeinträchtigt wird. Der Vorzug gilt dem Vermeiden von
247 | verschachtelten Anweisungen mit mehr als 20 Zeilen Länge.
248 | * Setze `@extend`-Angaben immer in die erste Zeile eines Deklarationsblocks.
249 | * Wo möglich gruppiere `@include`-Angaben am Anfang eines Deklarationsblocks,
250 | nach jedem `@extend`.
251 | * Ziehe in Betracht, eigenen Funktionen `x-` oder einen anderen Namensraum
252 | voranzustellen. Das hilft zu verhindern, dass deine Funktionen mit nativen
253 | CSS-Funktionen verwechselt werden oder mit Funktionen anderer Bibliotheken
254 | kollidieren.
255 |
256 | ```scss
257 | .selektor-1 {
258 | @extend .andere-regel;
259 | @include clearfix();
260 | @include box-sizing(border-box);
261 | width: x-grid-unit(1);
262 | // andere Deklarationen
263 | }
264 | ```
265 |
266 |
267 |
268 | ## 5. Praktisches Beispiel
269 |
270 | Ein Beispiel verschiedener Konventionen.
271 |
272 | ```css
273 | /* ==========================================================================
274 | Rasterlayout
275 | ========================================================================== */
276 |
277 | /**
278 | * Beispiel-Layout mit horizontalem Scrollen.
279 | *
280 | * Dies erzeugt eine Reihe von maximal-hohen, nicht umbrechenden Spalten, die
281 | * horizontal innerhalb ihres Elternelements durchsucht werden können.
282 | *
283 | * Beispiel-HTML:
284 | *
285 | *
286 | *
287 | *
288 | *
289 | *
290 | */
291 |
292 | /**
293 | * Grid-Container
294 | * Darf nur `.cell`-Kinder enthalten.
295 | */
296 |
297 | .grid {
298 | height: 100%;
299 | /* Verhindere Leerraum in Zellen */
300 | font-size: 0;
301 | /* Hindere inline-block-Zellen am Umbruch */
302 | white-space: nowrap;
303 | }
304 |
305 | /**
306 | * Grid-Zellen
307 | * Keine vorgegebene Breite. Erweitere mit `.cell-n`-Klassen.
308 | */
309 |
310 | .cell {
311 | position: relative;
312 | display: inline-block;
313 | overflow: hidden;
314 | box-sizing: border-box;
315 | height: 100%;
316 | /* Setzt den Abstand zwischen Zellen */
317 | padding: 0 10px;
318 | border: 2px solid #333;
319 | vertical-align: top;
320 | /* Stellt Leerraum wieder her */
321 | white-space: normal;
322 | /* Stellt Schriftgröße wieder her */
323 | font-size: 16px;
324 | }
325 |
326 | /* Zell-Zustände */
327 |
328 | .cell.is-animating {
329 | background-color: #fffdec;
330 | }
331 |
332 | /* Zell-Abmessungen
333 | ========================================================================== */
334 |
335 | .cell-1 { width: 10%; }
336 | .cell-2 { width: 20%; }
337 | .cell-3 { width: 30%; }
338 | .cell-4 { width: 40%; }
339 | .cell-5 { width: 50%; }
340 |
341 | /* Zell-Modifikatoren
342 | ========================================================================== */
343 |
344 | .cell--detail,
345 | .cell--important {
346 | border-width: 4px;
347 | }
348 | ```
349 |
350 |
351 |
352 | ## Danksagung
353 |
354 | Danke an alle, die Übersetzungen erstellt haben und all jene, die zu
355 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js) beigetragen haben. Es
356 | war eine Quelle der Inspiration, von Zitaten und Richtlinien.
357 |
358 |
359 |
360 | ## Lizenz
361 |
362 | _Grundlagen zum Schreiben von einheitlichem, idiomatischem CSS_ von Nicolas
363 | Gallagherist lizenziert unter der [Creative Commons Attribution 3.0
364 | Unported-License](http://creativecommons.org/licenses/by/3.0/). Dies trifft
365 | auf alle Dokumente und Übersetzungen in diesem Repository zu.
366 |
367 | Basierend auf einer Arbeit auf
368 | [github.com/necolas/idiomatic-css](https://github.com/necolas/idiomatic-css).
369 |
--------------------------------------------------------------------------------
/translations/es-ES/README.md:
--------------------------------------------------------------------------------
1 | # Principios para escribir CSS idiomático y consistente
2 |
3 | El siguiente documento ofrece una guía razonable de estilo para el desarrollo
4 | de CSS. No es mi intención ser preceptivo y no deseo imponer mis preferencias
5 | de estilo en el código de otras personas. Sin embargo esta guía anima
6 | enérgicamente a que se utilicen los patrones existentes, que son de sentido
7 | común.
8 |
9 | Este es un documento vivo y nuevas ideas son siempre bienvenidas. Por favor
10 | contribuya.
11 |
12 | [CSS idiomático en inglés (Original)](https://github.com/necolas/idiomatic-css/)
13 |
14 |
15 | ## Tabla de contenido
16 |
17 | 1. [Principios generales](#general-principles)
18 | 2. [Espacios en blanco](#whitespace)
19 | 3. [Comentarios](#comments)
20 | 4. [Formato](#format)
21 | 5. [Nomenclatura](#naming)
22 | 6. [Ejemplos prácticos](#example)
23 | 7. [Organización](#organization)
24 | 8. [Construcción y distribución](#build-and-deployment)
25 |
26 | [Agradecimientos](#acknowledgements)
27 |
28 |
29 |
30 | ## 1. Principios generales
31 |
32 | > "Parte de ser un buen administrador al crear un proyecto exitoso es darse
33 | > cuenta que escribir código para uno mismo es una Mala Idea™. Si miles de
34 | > personas están utilizando tu código, entonces escríbelo con la máxima
35 | > claridad, no con tus preferencias personales de cómo ser inteligente con la
36 | > especificación." - Idan Gazit
37 |
38 | * Todo el código en una aplicación debe parecer como si sólo una persona lo
39 | hubiese escrito, no importa cuántas personas hayan contribuido.
40 | * Fuerce a que se respete el estilo acordado.
41 | * Si tiene dudas utilice los patrones de uso común.
42 |
43 |
44 |
45 | ## 2. Espacios en blanco
46 |
47 | Sólo debe existir un estilo en el código de su proyecto. Siempre sea
48 | consistente en el uso de los espacios en blanco. Utilice espacios en blanco
49 | para mejorar la legibilidad.
50 |
51 | * _Nunca_ mezcle espacios y tabulaciones para indentar.
52 | * Elija entre indentaciones blandas (espacios) o tabulaciones reales. Apéguese
53 | a su elección sin fallo. (Preferencia: espacios)
54 | * Si utiliza espacios, elija el número de caracteres a usar para cada nivel de
55 | indentación. (Preferencia: 4 espacios)
56 |
57 | Consejo: configure su editor para que "muestre los caracteres invisibles". Esto
58 | le permitirá eliminar los espacios en blanco al final de las líneas, eliminar
59 | espacios en blanco de líneas en blanco y evitar commits con basura.
60 |
61 | Consejo: Utilice el editor [EditorConfig](http://editorconfig.org/) (o algún
62 | equivalente) para ayudarse a mantener las convenciones básicas que han sido
63 | acordadas en su proyecto.
64 |
65 |
66 |
67 | ## 3. Comentarios
68 |
69 | Un código bien comentado es muy importante. Tómese el tiempo necesario para
70 | describir los componente, cómo trabajan, sus limitaciones y la forma en que
71 | fueron construidos. No deje que otros miembros de su equipo tengan que adivinar
72 | el propósito de un código poco común o poco obvio.
73 |
74 | El estilo de los comentarios debe ser siempre simple y consistente con un mismo
75 | código base.
76 |
77 | * Coloque los comentarios en una línea nueva sobre cada objeto.
78 | * Evite los comentarios al final de las líneas.
79 | * Mantenga el largo de cada línea con un máximo razonable, por ejemplo, 80
80 | columnas.
81 | * Haga un uso libre de los comentarios para separar código CSS en secciones
82 | discretas.
83 | * Realice comentarios que comiencen con una letra mayúscula y con indentación
84 | consistente.
85 |
86 | Consejo: configure su editor para que le ofrezca atajos para la creación de
87 | comentarios comunes.
88 |
89 | #### Ejemplo de CSS:
90 |
91 | ```css
92 | /* ==========================================================================
93 | Bloque de comentario de sección
94 | ========================================================================== */
95 |
96 | /* Bloque de comentario de sub-sección
97 | ========================================================================== */
98 |
99 | /*
100 | * Pequeña descripción utilizando el formato de comentario Doxygen.
101 | *
102 | * La primer oración de una descripción larga comienza aquí y continúa en
103 | * esta linea durante un tiempo para finalmente terminar aquí al final de
104 | * este párrafo.
105 | *
106 | * Las descripciones largas son ideales para explicaciones de mayor detalle
107 | * y documentación. Pueden incluir ejemplos de HTML, URLs o cualquier otro
108 | * tipo de información que es considerada necesaria o útil.
109 | *
110 | * @tag Esto es una etiqueta llamada 'tag'
111 | *
112 | * @todo Esto es una declaración 'todo' ("a realizar") que describe una tarea
113 | * atómica (específica) a realizar posteriormente. Continua luego de 80
114 | * caracteres por lo que las lineas consecutivas son indentadas con dos
115 | * espacios adicionales.
116 | */
117 |
118 | /* Comentario básico */
119 | ```
120 |
121 |
122 |
123 | ## 4. Formato
124 |
125 | El formato del código elegido debe asegurarse de que el código: es fácil de
126 | leer, es fácil de comentar claramente, minimiza las posibilidades de introducir
127 | errores accidentalmente, y facilita el hallazgo de diferencias y
128 | responsabilidades.
129 |
130 | * Utilice un selector discreto por línea en un conjunto de reglas con multi
131 | selectores.
132 | * Incluya un solo espacio antes de la llave de apertura en un conjunto de
133 | reglas.
134 | * Incluya una declaración por línea en un bloque de declaraciones.
135 | * Utilice un nivel de indentación para cada declaración.
136 | * Incluya un solo espacio luego de los dos puntos en una declaración.
137 | * Utilice minúsculas y valores hexadecimales abreviados, ejemplo `#aaa`.
138 | * Utilice comillas simples o dobles pero de forma consistente. Se prefiere la
139 | utilización de comillas dobles, ejemplo `content: ""`.
140 | * Utilice comillas en los valores de los atributos de los selectores, ejemplo
141 | `input[type="checkbox"]`.
142 | * _Siempre que pueda_, evite especificar valores de 0, por ejemplo `margin:
143 | 0`.
144 | * Incluya un espacio luego de cada coma en las propiedades separadas por comas
145 | o en los valores de las funciones.
146 | * Siempre incluya un punto y coma al final de la línea de la última declaración
147 | en un bloque de declaraciones.
148 | * Coloque la llave de cierre de un conjunto de reglas en la misma columna que
149 | el primer carácter del conjunto.
150 | * Separe cada conjunto de reglas con una línea en blanco.
151 |
152 | ```css
153 | .selector-1,
154 | .selector-2,
155 | .selector-3[type="text"] {
156 | -webkit-box-sizing: border-box;
157 | -moz-box-sizing: border-box;
158 | box-sizing: border-box;
159 | display: block;
160 | font-family: helvetica, arial, sans-serif;
161 | color: #333;
162 | background: #fff;
163 | background: linear-gradient(#fff, rgba(0, 0, 0, 0.8));
164 | }
165 | ```
166 |
167 | #### Orden de las declaraciones
168 |
169 | Las declaraciones deben ser ordenadas con un único principio. Mi preferencia es
170 | que las propiedades relacionadas con la estructura (por ejemplo, de posición y
171 | box-model) sean declaradas antes que las demás.
172 |
173 | ```css
174 | .selector {
175 | /* Posicionamiento */
176 | position: absolute;
177 | z-index: 10;
178 | top: 0;
179 | right: 0;
180 | bottom: 0;
181 | left: 0;
182 |
183 | /* Display & Box Model */
184 | display: inline-block;
185 | overflow: hidden;
186 | box-sizing: border-box;
187 | width: 100px;
188 | height: 100px;
189 | padding: 10px;
190 | border: 10px solid #333;
191 | margin: 10px;
192 |
193 | /* Otras */
194 | background: #000;
195 | color: #fff
196 | font-family: sans-serif;
197 | font-size: 16px;
198 | text-align: right;
199 | }
200 | ```
201 |
202 | El ordenamiento alfabético es también muy popular, pero la desventaja es que
203 | las propiedades relacionadas no se mantienen juntas. Por ejemplo, los
204 | desplazamientos de posición no permanecen juntos y las propiedades de box-model
205 | pueden ser esparcidas a través del bloque de declaraciones.
206 |
207 | #### Excepciones y pequeñas desviaciones
208 |
209 | Bloques grandes de una sola declaración pueden ser ligeramente diferentes,
210 | utilizando el formato de una sola línea. En este caso, un espacio debe ser
211 | incluido luego de la llave de apertura y antes de la llave de cierre.
212 |
213 | ```css
214 | .selector-1 { width: 10%; }
215 | .selector-2 { width: 20%; }
216 | .selector-3 { width: 30%; }
217 | ```
218 |
219 | Grandes propiedades de valores separados por coma -tal como una colección de
220 | gradientes o sombras- pueden ser organizadas en múltiples líneas en un intento
221 | de mejorar la legibilidad y producir visualizaciones de diferencias más
222 | útiles. Hay varios formatos que pueden ser utilizados: uno, por ejemplo, es
223 | mostrado más abajo.
224 |
225 | ```css
226 | .selector {
227 | background-image:
228 | linear-gradient(#fff, #ccc),
229 | linear-gradient(#f3c, #4ec);
230 | box-shadow:
231 | 1px 1px 1px #000,
232 | 2px 2px 1px 1px #ccc inset;
233 | }
234 | ```
235 |
236 | ### Preprocesadores: consideraciones a formatos adicionales
237 |
238 | Cada preprocesador de CSS tiene sus características, funcionalidades y
239 | sintaxis. Sus convenciones deben extenderse para adaptarse a las
240 | particularidades de cada preprocesador en uso. La siguiente guía está referida
241 | a Sass.
242 |
243 | * Limítese a anidar con 1 nivel de profundidad. Corrija cualquier anidado de
244 | más de 2 niveles. Esto previene que existan selectores de CSS muy
245 | específicos.
246 | * Evite realizar un gran número de reglas anidadas. Sepárelas cuando la
247 | legibilidad comience a ser afectada. Se prefiere evitar el anidado que se
248 | extiende a más de 20 líneas.
249 | * Siempre coloque las declaraciones `@extend` en la primer línea de los bloques
250 | declarativos.
251 | * Dónde sea posible, agrupe las declaraciones `@include` en la parte superior
252 | del bloque declarativo, luego de las declaraciones `@extend`.
253 | * Considere prefijar funciones personalizadas con `x-` u otro separador. Esto
254 | ayuda a evitar cualquier confusión potencial con una función nativa de CSS, o
255 | entrar en conflicto con una función de alguna librería.
256 |
257 | ```scss
258 | .selector-1 {
259 | @extend .other-rule;
260 | @include clearfix();
261 | @include box-sizing(border-box);
262 | width: x-grid-unit(1);
263 | // other declarations
264 | }
265 | ```
266 |
267 |
268 |
269 | ## 5. Nomenclatura
270 |
271 | La nomenclatura es difícil, pero muy importante. Es una parte crucial del
272 | proceso de desarrollo y mantenimiento del proyecto, y le asegura a usted tener
273 | una relativamente escalable interfaz entre su código HTML y CSS.
274 |
275 | * Evite la _sistemática_ utilización de abreviaciones en los nombres de las
276 | clases. No haga las cosas difíciles de entender.
277 | * Utilice nombres claros y meditados para las _clases HTML_.
278 | * Elija un comprensible y consistente patrón de nombres que tengan sentido
279 | tanto para los archivos HTML como para los archivos CSS.
280 | * Los selectores para los componentes deben utilizar nombres de clases; evite
281 | la utilización de etiquetas genéricas e ids únicos.
282 |
283 |
284 | ```css
285 | /* Ejemplo de código con nombres incorrectos */
286 |
287 | .s-scr {
288 | overflow: auto;
289 | }
290 |
291 | .cb {
292 | background: #000;
293 | }
294 |
295 | /* Ejemplo de código con nombres correctos */
296 |
297 | .is-scrollable {
298 | overflow: auto;
299 | }
300 |
301 | .column-body {
302 | background: #000;
303 | }
304 | ```
305 |
306 |
307 |
308 | ## 6. Ejemplos prácticos
309 |
310 | Un ejemplo de varias convenciones.
311 |
312 | ```css
313 | /* ==========================================================================
314 | Grid layout
315 | ========================================================================== */
316 |
317 | /*
318 | * Ejemplo HTML:
319 | *
320 | *
324 | */
325 |
326 | .grid {
327 | overflow: visible;
328 | height: 100%;
329 | /* Prevent inline-block cells wrapping */
330 | white-space: nowrap;
331 | /* Remove inter-cell whitespace */
332 | font-size: 0;
333 | }
334 |
335 | .cell {
336 | box-sizing: border-box;
337 | position: relative;
338 | overflow: hidden;
339 | width: 20%;
340 | height: 100%;
341 | /* Set the inter-cell spacing */
342 | padding: 0 10px;
343 | border: 2px solid #333;
344 | vertical-align: top;
345 | /* Reset white-space */
346 | white-space: normal;
347 | /* Reset font-size */
348 | font-size: 16px;
349 | }
350 |
351 | /* Estados de las celdas */
352 |
353 | .cell.is-animating {
354 | background-color: #fffdec;
355 | }
356 |
357 | /* Dimensiones de las celdas
358 | ========================================================================== */
359 |
360 | .cell-1 { width: 10%; }
361 | .cell-2 { width: 20%; }
362 | .cell-3 { width: 30%; }
363 | .cell-4 { width: 40%; }
364 | .cell-5 { width: 50%; }
365 |
366 | /* Modificadores de celdas
367 | ========================================================================== */
368 |
369 | .cell--detail,
370 | .cell--important {
371 | border-width: 4px;
372 | }
373 | ```
374 |
375 |
376 |
377 | ## 7. Organización
378 |
379 | La organización del código es una parte importante en cualquier base de código
380 | CSS, y crucial para grandes bases de código.
381 |
382 | * Separe las distintas partes de código de forma lógica.
383 | * Utilice archivos independientes (unidos por un proceso de construcción) para
384 | ayudar a separar código para distintos componentes.
385 | * Si utiliza un preprocesador, abstraiga código común en variables para el
386 | color, la tipografía, etc.
387 |
388 |
389 |
390 | ## 8. Construcción y distribución
391 |
392 | Los proyectos deben siempre intentar incluir algunos medios genéricos para que
393 | el código pueda ser verificado, probado, comprimido y versionado para luego ser
394 | utilizado en producción. Para esta tarea,
395 | [grunt](https://github.com/cowboy/grunt), de Ben Alman es una excelente
396 | herramienta.
397 |
398 |
399 |
400 | ## Agradecimientos
401 |
402 | Gracias a todos los que han contribuido en
403 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js).
404 | Ha sido fuente de inspiración, referencia y guía.
405 |
--------------------------------------------------------------------------------
/translations/fr-FR/README.md:
--------------------------------------------------------------------------------
1 | # Principes d'écriture pour des CSS cohérents et idiomatiques
2 |
3 | Le présent document liste des recommandations raisonnables pour le
4 | développement CSS.
5 |
6 | Il n'est pas destiné à être normatif et je ne souhaite pas imposer mes
7 | préférences en matière de code à tout le monde. Toutefois, ces lignes
8 | directrices encouragent fortement l'utilisation de conventions existantes,
9 | communes et judicieuses.
10 |
11 | Ceci est un document évolutif et les nouvelles idées sont toujours les
12 | bienvenues.
13 |
14 | Merci de bien vouloir contribuer.
15 |
16 | [Idiomatic CSS en anglais](https://github.com/necolas/idiomatic-css/)
17 |
18 |
19 | ## Table des matières
20 |
21 | 1. [Principes généraux](#general-principles)
22 | 2. [Indentation](#whitespace)
23 | 3. [Commentaires](#comments)
24 | 4. [Format](#format)
25 | 5. [Nommage](#naming)
26 | 6. [Exemple pratique](#example)
27 | 7. [Organisation](#organization)
28 | 8. [Compilation et déploiement](#build-and-deployment)
29 |
30 | [Remerciements](#acknowledgements)
31 |
32 |
33 |
34 | ## 1. Principes généraux
35 |
36 | > Une des clefs d'une bonne gestion de projet est de réaliser qu'écrire du code
37 | > pour soi-même est une MAUVAISE IDÉE™. Si des milliers de personnes sont
38 | > amenées à utiliser votre code, alors écrivez votre code en visant un maximum
39 | > de clarté, et non en fonction de croyances personnelles comme la lecture de
40 | > spécifications qui rendrait plus intelligent." - Idan Gazit
41 |
42 | * Tout code présent dans n'importe quelle base de code doit avoir l'air d'avoir
43 | été écrit par une seule personne, peu importe le nombre de gens qui y ont
44 | contribué ;
45 | * Appliquez les conventions de style de manière stricte ;
46 | * En cas de doute, utilisez des conventions existantes et communes.
47 |
48 |
49 |
50 | ## 2. Indentation
51 |
52 | Une seule manière d‘indenter devrait être utilisée sur l'ensemble du code
53 | source de votre projet. Soyez toujours constant dans votre façon d‘indenter.
54 | Utilisez des espaces pour améliorer la lisibilité.
55 |
56 | * Ne mélangez _jamais_ les espaces et les tabulations pour l'indentation.
57 | * Choisissez entre des espaces ou de vraies tabulations. Tenez-vous en à votre
58 | choix sans y déroger. (Préference : espaces)
59 | * Si vous utilisez les espaces, choisissez le nombre de caractères utilisé pour
60 | chaque niveau d'indentation. (Préference : 4 espaces)
61 |
62 | Astuce : Configurez votre éditeur afin qu'il affiche les "caractères
63 | invisibles". Cela vous permettra de supprimer les espaces en fin de ligne, les
64 | espaces dans les lignes vides et évitera de polluer vos commits.
65 |
66 |
67 |
68 | ## 3. Commentaires
69 |
70 | Bien commenter son code est extrêmement important. Prenez le temps de décrire
71 | les composants, comment ils fonctionnent, leurs limites, et la manière dont ils
72 | sont conçus. Ne laissez pas les autres membres de l'équipe deviner le but d'un
73 | code inhabituel ou non trivial.
74 |
75 | La façon de commenter doit être simple et similaire dans toute base de code.
76 |
77 | * Placez les commentaires sur une nouvelle ligne au-dessus de leur sujet ;
78 | * Evitez les commentaires en fin de ligne ;
79 | * Gardez une longueur de ligne de taille raisonnable, par exemple 80
80 | caractères ;
81 | * Utilisez les commentaires comme bon vous semble pour diviser le code CSS en
82 | parties distinctes ;
83 | * Rédigez vos commentaires avec des majuscules et des minuscules et gardez une
84 | indentation constante pour le texte.
85 |
86 | Astuce: Paramètrez votre éditeur pour qu'il vous fournisse des raccourcis
87 | claviers qui produisent des commentaires conventionnels.
88 |
89 | #### Exemple en CSS :
90 |
91 | ```css
92 | /* ==========================================================================
93 | Bloc de commentaire de section
94 | ========================================================================== */
95 |
96 | /* Bloc de commentaire de sous-section
97 | ========================================================================== */
98 |
99 | /*
100 | * Groupe de bloc de commentaires.
101 | * Parfait pour les explications sur plusieurs lignes et la documentation.
102 | */
103 |
104 | /* Commentaire simple */
105 | ```
106 |
107 | #### SCSS exemple :
108 |
109 | ```scss
110 | // ==========================================================================
111 | // Bloc de commentaire de section
112 | // ==========================================================================
113 |
114 | // Bloc de commentaire de sous-section
115 | // ==========================================================================
116 |
117 | //
118 | // Groupe de bloc de commentaires.
119 | // Parfait pour les explications sur plusieurs lignes
120 | // et la documentation
121 |
122 | // Commentaire simple
123 | ```
124 |
125 |
126 |
127 | ## 4. Format
128 |
129 | Le format de code choisi doit assurer: une bonne lisibilité, des commentaires
130 | clairs, une réduction des probabilités d'insertion accidentelle d'erreurs, et
131 | la production de fichiers diff et de résolution des problèmes pratiques.
132 |
133 | 1. Un seul sélecteur par ligne dans les régles à plusieurs sélecteurs ;
134 | 2. Un espace avant l'accolade ouvrante d'une règle ;
135 | 3. Une déclaration par ligne dans un bloc de déclarations ;
136 | 5. Un espace après les deux points d'une déclaration ;
137 | 6. Ajoutez toujours un point-virgule à la fin de la dernière déclaration d’un
138 | bloc ;
139 | 7. Fermez l'accolade d'une règle au même niveau que le premier caractère de la
140 | règle ;
141 | 8. Sautez une ligne entre chaque règle.
142 |
143 | ```css
144 | .selecteur-1,
145 | .selecteur-2,
146 | .selecteur-3 {
147 | -webkit-box-sizing: border-box;
148 | -moz-box-sizing: border-box;
149 | box-sizing: border-box;
150 | display: block;
151 | color: #333;
152 | background: #fff;
153 | }
154 | ```
155 |
156 | #### Ordre des déclarations
157 |
158 | L'ordre des déclarations doit toujours obéir à la même règle. Je préfère
159 | regrouper les règles connexes ensemble et déclarer les propriétés importantes
160 | relatives à la structure (c-à-d le positionnement et le modèle de boîte) avant
161 | les règles typographiques, l'arrière-plan et les couleurs.
162 |
163 | ```css
164 | .selecteur {
165 | position: relative;
166 | display: block;
167 | width: 50%;
168 | height: 100px;
169 | padding: 10px;
170 | border: 0;
171 | margin: 10px;
172 | color: #fff
173 | background: #000;
174 | }
175 | ```
176 |
177 | L'ordre alphabétique est également très utilisé, mais le problème est qu'il
178 | sépare les propriétés liées. Par exemple, les décalages de positionnement ne
179 | sont plus regroupés ensemble et les propriétés du modèle de boîte se retrouvent
180 | éparpillées dans le bloc de déclaration.
181 |
182 | #### Exceptions et légers écarts
183 |
184 | De gros blocs de déclarations uniques peuvent utiliser un format légèrement
185 | différent, regroupées sur une seule ligne. Dans ce cas, il faut insérer un
186 | espace après l'accolade ouvrante et avant l'accolade fermante.
187 |
188 | ```css
189 | .selecteur-1 { width: 10%; }
190 | .selecteur-2 { width: 20%; }
191 | .selecteur-3 { width: 30%; }
192 | ```
193 |
194 | Les longues valeurs de propriétés, séparées par des virgules - comme des
195 | ensembles de dégradés et d'ombres - peuvent être agencées sur plusieurs lignes
196 | de manière à améliorer la lisibilité et produire des fichiers diff plus utiles.
197 | Divers formats peuvent alors être utilisés comme le montre l'exemple donné
198 | ci-dessous :
199 |
200 | ```css
201 | .selecteur {
202 | box-shadow:
203 | 1px 1px 1px #000,
204 | 2px 2px 1px 1px #ccc inset;
205 | background-image:
206 | linear-gradient(#fff, #ccc),
207 | linear-gradient(#f3c, #4ec);
208 | }
209 | ```
210 |
211 | #### Divers
212 |
213 | * Utilisez des minuscules pour les valeurs hexadécimales, exemple : `#aaa` ;
214 | * Utilisez toujours le même type de guillemets. Ma préférence va aux doubles
215 | guillemets, exemple : `content: ""` ;
216 | * Utilisez toujours des guillemets pour les valeurs dans les sélecteurs,
217 | exemple : `input[type="checkbox"]` ;
218 | * _Lorsque c'est autorisé_, évitez de spécifier les unités pour les valeurs
219 | nulles, exemple : `margin: 0`.
220 |
221 | ### Préprocesseurs: considérations additionnelles pour le formatage
222 |
223 | Les différents préprocesseurs CSS offrent des possibilités, des fonctionnalités
224 | et une syntaxe différentes. Vos conventions doivent être étendues pour
225 | s'adapter aux particularités des préprocesseurs que vous utilisez. Les
226 | conventions suivantes font référence à Sass.
227 |
228 | * Limiter l'imbrication à un niveau de profondeur. Réexaminez toute imbrication
229 | supérieure à deux niveaux de profondeur. Cela évite des sélecteurs CSS trop
230 | spécifiques.
231 | * Evitez d'imbriquer un trop grand nombre de règles, séparez les lorsque cela
232 | nuit à la lisibilité. Je préfère éviter les imbrications qui dépassent les 20
233 | lignes.
234 | * Placez toujours les déclarations "@extend" en début de bloc.
235 | * Si possible, regroupez toutes les déclarations "@include" en début de bloc
236 | juste après les déclarations "@extend".
237 | * Pensez à préfixer vos propres fonctions avec `x-` ou un autre espace de nom.
238 | Cela permet d'éviter potentiellement de confondre votre fonction avec une
239 | fonction native CSS, ou les conflits avec des fonctions provenant de
240 | bibliothèques.
241 |
242 | ```scss
243 | .selecteur-1 {
244 | @extend .other-rule;
245 | @include clearfix();
246 | @include box-sizing(border-box);
247 | width: x-grid-unit(1);
248 | // other declarations
249 | }
250 | ```
251 |
252 |
253 |
254 | ## 5. Nommage
255 |
256 | Vous n'êtes pas un compilateur/compresseur de code humain, alors ne prétendez
257 | pas en être un.
258 |
259 | Utilisez des noms clairs et réfléchis pour les classes HTML. Choisissez un
260 | modèle de nommage cohérent et compréhensif qui a du sens à la fois dans les
261 | fichiers HTML et dans les fichiers CSS.
262 |
263 | ```css
264 | /* Exemple de code mal nommé */
265 |
266 | .s-scr {
267 | overflow: auto;
268 | }
269 |
270 | .cb {
271 | background: #000;
272 | }
273 |
274 | /* Exemple de code bien nommé */
275 |
276 | .is-scrollable {
277 | overflow: auto;
278 | }
279 |
280 | .column-body {
281 | background: #000;
282 | }
283 | ```
284 |
285 |
286 |
287 | ## 6. Exemple pratique
288 |
289 | Un exemple de divers conventions.
290 |
291 | ```css
292 | /* ==========================================================================
293 | Construction de la grille
294 | ========================================================================== */
295 |
296 | /*
297 | * Exemple de code HTML:
298 | *
299 | *
303 | */
304 |
305 | .grid {
306 | overflow: visible;
307 | height: 100%;
308 | /* Évite d'entourer les cellules avec un inline-block */
309 | white-space: nowrap;
310 | /* Suppression des espaces entre les cellules */
311 | font-size: 0;
312 | }
313 |
314 | .cell {
315 | box-sizing: border-box;
316 | position: relative;
317 | overflow: hidden;
318 | width: 20%;
319 | height: 100%;
320 | /* Définition de l'espacement entre les cellules */
321 | padding: 0 10px;
322 | border: 2px solid #333;
323 | vertical-align: top;
324 | /* Réinitialisation de la gestion des espaces */
325 | white-space: normal;
326 | /* Réinitialisation de la taille de police */
327 | font-size: 16px;
328 | }
329 |
330 | /* Etats des cellules */
331 |
332 | .cell.is-animating {
333 | background-color: #fffdec;
334 | }
335 |
336 | /* Dimensions des cellules
337 | ========================================================================== */
338 |
339 | .cell-1 { width: 10%; }
340 | .cell-2 { width: 20%; }
341 | .cell-3 { width: 30%; }
342 | .cell-4 { width: 40%; }
343 | .cell-5 { width: 50%; }
344 |
345 | /* Styles de cellule
346 | ========================================================================== */
347 |
348 | .cell--detail,
349 | .cell--important {
350 | border-width: 4px;
351 | }
352 | ```
353 |
354 |
355 |
356 | ## 7. Organisation
357 |
358 | L'organisation du code est une partie importante de n'importe quelle base de
359 | code CSS et devient cruciale pour les grosses bases de code.
360 |
361 | * Séparez de manière logique les différentes parties de code ;
362 | * Utilisez des fichiers distincts (concaténés au cours de l'étape de
363 | compilation) pour aider à découper le code en différents composants ;
364 | * Si vous utilisez un préprocesseur, stockez le code récurrent dans des
365 | variables pour la couleur, la typographie, etc.
366 |
367 |
368 |
369 | ## 8. Compilation et déploiement
370 |
371 | Les projets devraient toujours essayer de mentionner des façons génériques
372 | grâce auxquelles le code source peut être validé, testé, compressé et versionné
373 | en préparation à l'utilisation en production. Pour cela,
374 | [grunt](https://github.com/cowboy/grunt) de Ben Alman est un excellent outil.
375 |
376 |
377 |
378 | ## Remerciements
379 |
380 | Merci à tous ceux qui ont contribué à
381 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js). Cela a été une source
382 | d'inspiration, de citations et de conventions.
383 |
--------------------------------------------------------------------------------
/translations/id-ID/README.md:
--------------------------------------------------------------------------------
1 | # Prinsip Penulisan CSS yang Konsisten, Idiomatic
2 |
3 | Dokumen dibawah ini menjelaskan petunjuk umum dalam pengembangan CSS. Petunjuk
4 | ini sangat mengutamakan penggunaan pola umum yang ada. Dan sebaiknya digunakan
5 | dalam Penulisan CSS sesuai kebutuhan anda.
6 |
7 | Dokumen ini sedang digunakan oleh banyak orang, dan sangat terbuka dengan saran
8 | yang masuk. Silahkan berpartisipasi.
9 |
10 |
11 | ## Daftar Isi
12 |
13 | 1. [Prinsip Umum](#general-principles)
14 | 2. [Whitespace](#whitespace)
15 | 3. [Komentas](#comments)
16 | 4. [Format](#format)
17 | 5. [Contoh Penggunaan](#example)
18 |
19 | [Lisensi](#license)
20 |
21 | [Kontribusi & Saran](#contribute)
22 |
23 |
24 |
25 | ## 1. Prinsip Umum
26 |
27 | > "Salah satu bagian untuk menjadi staf yang baik dalam Proyek adalah memahami
28 | > bahwa menulis kode untuk diri sendiri adalah hal yang buruk. Jika ribuan
29 | > sedang menggunakan kode anda, maka tulislah kode anda dengan jelas dan
30 | > objektif, jangan menggunakan cara pribadi dalam memahami kode." - Idan
31 | > Gazit
32 |
33 | * Jangan mencoba menjadi manusia Compiler.
34 | * Semua kode harus tampak seperti ditulis oleh satu orang, walaupun ada banyak
35 | orang yang berpartisipasi.
36 | * Melaksanakan pola yang disepakati dengan ketat.
37 | * Jika ragu dengan pola tersebut, gunakan pola yang ada dan umum.
38 |
39 |
40 |
41 | ## 2. Whitespace
42 |
43 | Anda disarankan menggunakan satu pola dalam seluruh kode. Harap konsisten
44 | dengan penggunaan whitespace pada kode. Gunakan Whitespace untuk memudahkan
45 | pembacaan kode.
46 |
47 | * _Hindari_ membaurkan Spasi dan Tab untuk indentasi.
48 | * Pilih salah satu antara _Soft Indents_ (Spasi) atau Tab original. Yakinlah
49 | akan pilihan anda. (Disarankan: Spasi)
50 | * Jika menggunakan Spasi, pilih jumlah karakter yang digunakan ditiap
51 | indentasi. (Disarankan: 4 Spasi)
52 |
53 | Tip: Setting Editor anda untuk mengaktifkan "show invisibles". Hal ini
54 | meperbolehkan anda menghapus whitespace yang tidak diinginkan.
55 |
56 | Tip: Gunakan File [EditorConfig](http://editorconfig.org) (atau yang sejenis)
57 | untuk membantu pengaturan Whitespace yang anda gunakan pada kode anda.
58 |
59 |
60 |
61 | ## 3. Komentar
62 |
63 | Kode yang dikomentari dengan baik sangatlah penting. Sisihkan waktu untuk
64 | menjelaskan komponen, bagaimana mereka bekerja, dan cara penggunaannya. Jangan
65 | membiarkan staf di Tim anda untuk menduga-duga atau menebak-nebak karena kode
66 | yang kurang jelas.
67 |
68 | Pola Komentar harus sederhana dan konsisten di setiap kode anda.
69 |
70 | * Tempatkan Komentar di atas subjeknya.
71 | * Tetapkan standar panjang karakter ditiap Komentar. Contoh: 80 Karakter
72 | * Anda bebas untuk menentukan Komentar sebagai pemecah kode CSS menjadi
73 | beberapa bagian.
74 | * Gunakan "Sentence Case" pada Komentar dan penggunaan indentasi yang konsisten
75 |
76 | Tip: Buat snippet pada Editor anda sebagai shortcut untuk Komentar yang akan
77 | anda gunakan.
78 |
79 | Contoh:
80 | ```css
81 | /* ==========================================================================
82 | Blok Bagian
83 | ========================================================================== */
84 |
85 | /* Blok Sub-Bagian
86 | ========================================================================== */
87 |
88 | /**
89 | * Deskripsi Singkat menggunakan format Komentar Doxygen-style
90 | *
91 | * Kalimat pertama dari Deskripsi Detail dimulai di sini dan berlanjut di baris
92 | * selanjutnya hingga sampai kepada kesimpulan pada akhir paragraf.
93 | *
94 | * Deskripsi Detail sangat ideal untuk Penjelasan yang lebih lengkap dan
95 | * sebagai Dokumentasi. Disini anda dapat memasukkan contoh HTML, URL, atau
96 | * informas-informasi lain yang berguna untuk penjelasan.
97 | *
98 | * @tag Tag ini dinamakan 'tag'
99 | *
100 | * @todo Ini adalah Statemen Todo yang mendeskripsikan tugas-tugas yang harus
101 | * anda selesaikan di waktu yang akan datang. Bagian ini memilik panjang
102 | * maksimal 80 karakter dan baris dibawahnya di indentasi menggunakan 2 spasi
103 | */
104 |
105 | /* Komentar standar */
106 | ```
107 |
108 |
109 |
110 | ## 4. Format
111 |
112 | Format kode yang anda gunakan harus memastikan bahwa kode tersebut: mudah
113 | dibaca; mudah di-Komentari; meminimalkan kemungkinan kesalahan penggunaan;
114 | dan menghasil _diff_ dan _blame_ yang berguna.
115 |
116 | * Gunakan satu baris per selector, dalam deklarasi rule multi-selector.
117 | * Masukkan satu Spasi sebelum Buka Kurung dalam deklarasi rule.
118 | * Gunakan deklarasi per baris dalam blok deklarasi.
119 | * Gunakan satu level indentasi di tiap blok deklarasi.
120 | * Masukkan satu Spasi setelah tanda Titik Koma dalam deklarasi.
121 | * Gunakan _lowercase_ untuk Short Nilai Hex. Contoh: `#aaa`.
122 | * Gunakan salah satu dari tanda Kutip Satu atau Kutip Dua secara konsisten.
123 | Disarankan Tanda Kutip Dua. Contoh: `content: ""`.
124 | * Gunakan tanda kutip pada Nilai dari Attribute Selector. Contoh:
125 | `input[type="checkbox"]`.
126 | * _Jika Memungkinkan_ hindari memberi satuan unit pada Nilai Nol. Contoh:
127 | `margin: 0`.
128 | * Masukkan satu Spasi setelah Koma dalam Comma-Separated properti atau nilai
129 | function.
130 | * Tetap ikutkan Titik Koma setelah deklarasi properti akhir di dalam blok
131 | deklarasi.
132 | * Tempatkan tanda Tutup Kurung `}` pada blok deklarasi sesuai dengan posisi
133 | kolom tanda Buka Kurung `{`.
134 | * Pisahkan tiap blok deklarasi dengan Baris Kosong.
135 |
136 | ```css
137 | .selector-1,
138 | .selector-2,
139 | .selector-3[type="text"] {
140 | -webkit-box-sizing: border-box;
141 | -moz-box-sizing: border-box;
142 | box-sizing: border-box;
143 | display: block;
144 | font-family: helvetica, arial, sans-serif;
145 | color: #333;
146 | background: #fff;
147 | background: linear-gradient(#fff, rgba(0, 0, 0, 0.8));
148 | }
149 |
150 | .selector-a,
151 | .selector-b {
152 | padding: 10px;
153 | }
154 | ```
155 |
156 | #### Urutan Deklarasi
157 |
158 | Jika anda mengurutkan deklarasi properti, maka anda harus menggunakan aturan
159 | sederhana. Saran saya anda harus mendahulukan properti yang lebih penting
160 | seperti Positioning, Box Model.
161 |
162 | ```css
163 | .selector {
164 | /* Positioning */
165 | position: absolute;
166 | z-index: 10;
167 | top: 0;
168 | right: 0;
169 | bottom: 0;
170 | left: 0;
171 |
172 | /* Display & Box Model */
173 | display: inline-block;
174 | overflow: hidden;
175 | box-sizing: border-box;
176 | width: 100px;
177 | height: 100px;
178 | padding: 10px;
179 | border: 10px solid #333;
180 | margin: 10px;
181 |
182 | /* Other */
183 | background: #000;
184 | color: #fff;
185 | font-family: sans-serif;
186 | font-size: 16px;
187 | text-align: right;
188 | }
189 | ```
190 |
191 | Pengurutan propery berdasarkan Huruf juga cukup populer, tetapi kekurangannya
192 | adalah dia memisahkan properti yang berhubungan. Contoh properti pendukung
193 | dari position tidak lagi dikelompokkan bersama-sama dan akan menyebar di
194 | seluruh blok deklarasi.
195 |
196 | #### Pengecualian
197 |
198 | Blok panjang dari deklarasi tunggal dapat ditulis secara berbeda, format satu
199 | baris. Dalam kasus ini, satu Spasi dimasukkan setelah tanda Buka Kurung `{` dan
200 | sebelum tanda Tutup Kurung `}`.
201 |
202 | ```css
203 | .selector-1 { width: 10%; }
204 | .selector-2 { width: 20%; }
205 | .selector-3 { width: 30%; }
206 | ```
207 |
208 | Nilai yang cukup panjang, Comma-separated seperti Nilai font-family, gradient,
209 | dan box shadow dapat ditulis dengan memisahkan per baris dengan tujuan
210 | memudahkan cara pembacaan dan menghasilkan diff yang berkualitas. Banyak format
211 | yang dapat digunakan, berikut adalah salah satu contoh.
212 |
213 | ```css
214 | .selector {
215 | background-image:
216 | linear-gradient(#fff, #ccc),
217 | linear-gradient(#f3c, #4ec);
218 | box-shadow:
219 | 1px 1px 1px #000,
220 | 2px 2px 1px 1px #ccc inset;
221 | }
222 | ```
223 |
224 | ### Preprocessor: Tambahan Pertimbangan Format
225 |
226 | CSS Preprocessor Berbeda juga mempunyai fitur, fungsi, dan syntax yang berbeda.
227 | Aturan pola kode anda harus memadai dan cocok di tiap CSS Preprocessor.
228 | Petunjuk di bawah ini di adaptasi dari petunjuk SASS.
229 |
230 | * Batasi sarang _(nesting)_ satu level lebih dalam. Deklarasi kan deklarasi
231 | blok yang melebihi dua level sarang. Hal ini mencegah selector menjadi
232 | terlalu spesifik.
233 | * Hindari menggunakan deklarasi rule bersarang yang berlebihan. Pisahkan
234 | secepatnya ketika sudah mulai mengurangi tingkat kemudahan pembacaan kode.
235 | Saran, hindari menggunakan deklarasi rule bersarang jika rulenya melebihi dari
236 | 20 baris.
237 | * Selalu tempatkan statemen `@extend` pada baris pertama dari blok deklarasi.
238 | * Jika memungkinkan, tempatkan `@include` statemen pada baris awal setelah
239 | `@extend` statemen.
240 | * Pertimbangkan menggunakan prefix `x-` atau prefix lainnya jika menggunakan
241 | fungsi buatan. Hal ini membantu menghindari kebingungan menggunakan fungsi
242 | asli dari CSS atau konflik dengan fungsi dari librari yang anda gunakan.
243 |
244 | ```scss
245 | .selector-1 {
246 | @extend .other-rule;
247 | @include clearfix();
248 | @include box-sizing(border-box);
249 | width: x-grid-unit(1);
250 | // other declarations
251 | }
252 | ```
253 |
254 |
255 |
256 | ## 5. Contoh Penggunaan
257 |
258 | Sebuah contoh dari aturan kode yang beragam.
259 |
260 | ```css
261 | /* ==========================================================================
262 | Grid layout
263 | ========================================================================== */
264 |
265 | /**
266 | * Column layout dengan horizontal scroll.
267 | *
268 | * Ini membuat satu baris full-height, non-wrap kolom yang bisa digunakan
269 | * horizontal dengan parent mereka.
270 | *
271 | * Contoh HTML:
272 | *
273 | *
274 | *
275 | *
276 | *
277 | *
278 | */
279 |
280 | /**
281 | * Grid container
282 | * Harus diisi oleh `.cell`
283 | */
284 |
285 | .grid {
286 | height: 100%;
287 | /* Hilangkan inter-cell whitespace */
288 | font-size: 0;
289 | /* Cegah wrapping inline-block */
290 | white-space: nowrap;
291 | }
292 |
293 | /**
294 | * Grid cells
295 | * Tidak ada spesifik width secara default. Extend dengan `.cell-n` class
296 | */
297 |
298 | .cell {
299 | position: relative;
300 | display: inline-block;
301 | overflow: hidden;
302 | box-sizing: border-box;
303 | height: 100%;
304 | /* Set inter-cell spasi */
305 | padding: 0 10px;
306 | border: 2px solid #333;
307 | vertical-align: top;
308 | /* Reset white-space */
309 | white-space: normal;
310 | /* Reset font-size */
311 | font-size: 16px;
312 | }
313 |
314 | /* Cell states */
315 |
316 | .cell.is-animating {
317 | background-color: #fffdec;
318 | }
319 |
320 | /* Dimensi Cell
321 | ========================================================================== */
322 |
323 | .cell-1 { width: 10%; }
324 | .cell-2 { width: 20%; }
325 | .cell-3 { width: 30%; }
326 | .cell-4 { width: 40%; }
327 | .cell-5 { width: 50%; }
328 |
329 | /* Cell Pengubah
330 | ========================================================================== */
331 |
332 | .cell--detail,
333 | .cell--important {
334 | border-width: 4px;
335 | }
336 | ```
337 |
338 |
339 |
340 | ## Lisensi
341 |
342 | _Principles of writing consistent, idiomatic CSS_ oleh Nicolas Gallagher
343 | dirilis dengan lisensi [Creative Commons Attribution 3.0 Unported
344 | License](http://creativecommons.org/licenses/by/3.0/). Lisensi ini berlaku
345 | untuk semua dokumen dan terjemahan di repository.
346 |
347 | Dibuat berdasarkan proyek di
348 | [github.com/necolas/idiomatic-css](https://github.com/necolas/idiomatic-css).
349 |
350 |
351 |
352 | ## Kontribusi & Saran
353 |
354 | Jika anda ingin berpartisipasi dalam Proyek Penerjemahan ini, silahkan fork
355 | [Idiomatic](http://github.com/novrian/idiomatic_id-ID).
356 |
--------------------------------------------------------------------------------
/translations/it-IT/README.md:
--------------------------------------------------------------------------------
1 | # Princìpi per la scrittura di CSS consistente ed idiomatico
2 |
3 | L'intento di questo documento è quello di esporre una ragionevole guida allo
4 | stile per lo sviluppo del CSS. Queste linee guida incoraggiano al riutilizzo di
5 | pattern già esistenti ed ampiamente testati dalla comunità. Si dovrebbe
6 | cercare, infine, di adattare questi pattern alle proprie necessità in modo da
7 | creare proprie regole ed un proprio stile.
8 |
9 | Questo è un documento in continua evoluzione e nuove idee sono sempre bene
10 | accette. Per favore contribuite.
11 |
12 | [Leggi la versione originale in inglese](https://github.com/necolas/idiomatic-css)
13 |
14 |
15 | ## Tavola dei contenuti
16 |
17 | 1. [Princìpi generali](#general-principles)
18 | 2. [Spazio vuoto](#whitespace)
19 | 3. [Commenti](#comments)
20 | 4. [Formato](#format)
21 | 5. [Esempio pratico](#example)
22 |
23 | [Ringraziamenti](#acknowledgments)
24 |
25 | [Licenza](#license)
26 |
27 |
28 |
29 | ## 1. Princìpi generali
30 |
31 | > "Parte dell'essere un buon amministratore in un progetto votato al successo è
32 | > capire che la scrittura di codice per sé stessi è una Cattiva Idea™. Se
33 | > migliaia di persone usano il tuo codice, allora scrivi il tuo codice in modo
34 | > che abbia la massima chiarezza, e non seguendo i tuoi gusti personali su come
35 | > renderlo chiaro all'interno delle specifiche" - Idan Gazit
36 |
37 | * Non cercare di ottimizzare in anticipo il tuo codice; cerca di mantenerlo
38 | leggibile e comprensibile.
39 | * Tutto il codice, in qualsiasi linguaggio sia, dovrebbe sembrare come scritto
40 | da un'unica persona, anche quando molte persone vi stanno contribuendo.
41 | * Rispettate al massimo lo stile prescelto.
42 | * Nel dubbio, usate pattern comuni già esistenti e collaudati.
43 |
44 |
45 |
46 | # 2. Spazio vuoto
47 |
48 | Dovrebbe esistere solo uno stile in tutto il sorgente del vostro progetto.
49 | Siate sempre consistenti nell'uso dello spazio vuoto. Usate questo spazio per
50 | migliorare la leggibilità.
51 |
52 | * _Mai_ mischiare spazi e tabulazioni per i rientri.
53 | * Scegliete tra rientri soft (spazi) o tabulazioni reali. Mantenete quella
54 | scelta (preferenza: spazi).
55 | * Se usate gli spazi, scegliete il numero di caratteri usati per il livello di
56 | rientro (preferenza: 4 spazi).
57 |
58 | Suggerimento: configurate il vostro editor in modo da "visualizzare i caratteri
59 | invisibili" o rimuovere automaticamente gli spazio vuoti a fine linea.
60 |
61 | Suggerimento: usate un file [EditorConfig](http://editorconfig.org/) (o
62 | equivalente) per aiutarvi a mantenere le convenzioni di base relative allo
63 | spazio vuoto che si è scelto di usare per il vostro codice.
64 |
65 |
66 |
67 | ## 3. Commenti
68 |
69 | Un codice ben commentato è estremamente importante. Prendetevi il tempo
70 | necessario per descrivere i vari componenti, come funzionano, i loro limiti, ed
71 | il modo in cui sono stati costruiti. Non create una situazione nella quale
72 | altri membri del vostro team debbano cercare di immaginare il motivo ed il
73 | funzionamento di codice non comune o poco chiaro.
74 |
75 | Lo stile di un commento dovrebbe essere semplice e consistente all'interno di
76 | una singola base di codice.
77 |
78 | * Mettete i commenti su di una nuova linea che preceda il relativo soggetto.
79 | * Mantenete una lunghezza massima per le linee, es. 80 colonne.
80 | * Fate libero uso di commenti per spezzare il codice CSS in sezioni logiche più
81 | piccole.
82 | * Fate un uso corretto e consistente della grammatica, delle maiuscole e dei
83 | rientri.
84 |
85 | Suggerimento: configurate il vostro editor in modo che vi fornisca delle
86 | scorciatoie per la gestione di pattern predefiniti per i commenti.
87 |
88 | Esempio:
89 |
90 | ```css
91 | /* ==========================================================================
92 | Sezione blocco commento
93 | ========================================================================== */
94 |
95 | /* Sotto sezione blocco commento
96 | ========================================================================== */
97 |
98 | /**
99 | * Breve descrizione utilizzando un formato nei commenti in stile Doxygen
100 | *
101 | * La prima frase di una lunga descrizione inizia qui e continua su questa
102 | * linea per un po' fino alla sua conclusione qui alla fine di questo paragrafo.
103 | *
104 | * Una lunga descrizione è ideale per una più dettagliata spiegazione e
105 | * documentazione. Essa può includere esempi in HTML, URL o qualsiasi altra
106 | * informazione che riteniate importante o utile.
107 | *
108 | * @tag Questo è un 'tag'
109 | *
110 | * TODO: Questa è una dichiarazione 'todo' che descrive un'attività necessaria
111 | * che dovrà essere completata in un momento successivo. Essa va a capo dopo
112 | * 80 caratteri e le linee successive vengono rientrare di 2 spazi.
113 | */
114 |
115 | /* Commento base */
116 | ```
117 |
118 |
119 |
120 | ## 4. Formato
121 |
122 | Il formato scelto deve far sì che il codice: sia facile da leggere; sia facile
123 | da commentare in modo chiaro; minimizzi la possibilità di introdurre
124 | accidentalmente errori; dia risultati utili nei diff e blame.
125 |
126 | * Un solo selettore per linea in set di regole con più selettori.
127 | * Un singolo spazio prima della parentesi graffa di apertura di un set di
128 | regole.
129 | * Una dichiarazione per linea in un blocco dichiarativo.
130 | * Un livello di rientro per ogni dichiarazione.
131 | * Un singolo spazio dopo i due-punti di una dichiarazione.
132 | * Usate valori esadecimali in minuscolo ed in forma abbreviata, es. `#aaa`.
133 | * Usate apici e doppi apici in modo uniforme. La preferenza è per i doppi
134 | apici, es. `content: ""`.
135 | * Racchiudete in doppi apici i valori nei selettori, es.
136 | `input[type="checkbox"]`.
137 | * _Dove possibile_, evitate di specificare l'unità di misura per valori uguali
138 | a zero, es. `margin: 0`.
139 | * Includete uno spazio dopo ogni virgola, per le liste di proprietà separate da
140 | virgola o per i valori nelle funzioni.
141 | * Includete un punto-e-virgola alla fine dell'ultima dichiarazione in un blocco
142 | dichiarativo.
143 | * Mettete la parentesi graffa di chiusura di un set di regole, nella stessa
144 | colonna del primo carattere del set di regole.
145 | * Separate ogni set di regole con una linea vuota.
146 |
147 | ```css
148 | .selector-1,
149 | .selector-2,
150 | .selector-3[type="text"] {
151 | -webkit-box-sizing: border-box;
152 | -moz-box-sizing: border-box;
153 | box-sizing: border-box;
154 | display: block;
155 | font-family: helvetica, arial, sans-serif;
156 | color: #333;
157 | background: #fff;
158 | background: linear-gradient(#fff, rgba(0, 0, 0, 0.8));
159 | }
160 |
161 | .selector-a,
162 | .selector-b {
163 | padding: 10px;
164 | }
165 | ```
166 |
167 | #### Ordine di dichiarazione
168 |
169 | Se le dichiarazioni devono essere ordinate in modo logico, esse dovrebbero
170 | seguire un semplice ed unico criterio.
171 |
172 | I piccoli team potrebbero preferire il raggruppamento delle proprietà (es.
173 | posizionamento e box-model) per categoria.
174 |
175 | ```css
176 | .selector {
177 | /* Posizionamento */
178 | position: relative;
179 | z-index: 10;
180 | top: 0;
181 | right: 0;
182 | bottom: 0;
183 | left: 0;
184 |
185 | /* Visualizzazione e box-model */
186 | display: inline-block;
187 | overflow: hidden;
188 | box-sizing: border-box;
189 | width: 100px;
190 | height: 100px;
191 | padding: 10px;
192 | border: 10px solid #333;
193 | margin: 10px;
194 |
195 | /* Altro */
196 | background: #000;
197 | color: #fff;
198 | font-family: sans-serif;
199 | font-size: 16px;
200 | text-align: right;
201 | }
202 | ```
203 |
204 | I grossi team potrebbero preferire la semplicità e facilità di manutenzione che
205 | deriva dall'ordinamento alfabetico.
206 |
207 |
208 | #### Eccezioni e piccole deviazioni
209 |
210 | Grossi blocchi di dichiarazioni di una sola linea, possono usare un formato
211 | leggermente differente, a linea singola. In questo caso, uno spazio dovrebbe
212 | essere messo dopo la parentesi graffa di apertura e prima di quella di
213 | chiusura.
214 |
215 | ```css
216 | .selector-1 { width: 10%; }
217 | .selector-2 { width: 20%; }
218 | .selector-3 { width: 30%; }
219 | ```
220 |
221 | Lunghe liste di valori di proprietà separate da virgole - come una collezione
222 | di sfumature od ombre - possono essere suddivisi su più linee nel tentativo di
223 | migliorarne la leggibilità e produrre diff più utili. Ci sono vari formati che
224 | potrebbero essere usati; di seguito ne viene mostrato un esempio.
225 |
226 | ```css
227 | .selector {
228 | background-image:
229 | linear-gradient(#fff, #ccc),
230 | linear-gradient(#f3c, #4ec);
231 | box-shadow:
232 | 1px 1px 1px #000,
233 | 2px 2px 1px 1px #ccc inset;
234 | }
235 | ```
236 |
237 | ### Preprocessori: ulteriori considerazioni sul formato
238 |
239 | Ogni preprocessore per CSS ha le sue caratteristiche, funzionalità e sintassi.
240 | Le vostre convenzioni dovrebbero adattarsi per venire in contro alle
241 | particolarità del preprocessore in uso. Quelle che seguono sono le linee guida
242 | prendendo come riferimento Sass.
243 |
244 | * Limitate la nidificazione ad 1 livello di profondità. Riarrangiate ogni
245 | nidificazione con 2 o più livelli di profondità. Questo previene la creazione
246 | di selettori CSS inutilmente troppo specifici.
247 | * Evitate un numero elevato di regole nidificate. Spezzatele in blocchi logici
248 | più piccoli quando cominciate a rendervi conto che la leggibilità inizia a
249 | risentirne. Preferite di evitare nidificazioni che siano più lunghe di 20
250 | linee.
251 | * Come prima cosa in un blocco dichiarativo, mettete sempre le dichiarazioni
252 | `@extend`.
253 | * Dove possibile, raggruppate le dichiarazioni `@include` all'inizio di un
254 | blocco dichiarativo, subito dopo le dichiarazioni `@extend`.
255 | * Considerate l'idea di anteporre una `x-` o un altro namespace alle funzioni
256 | personalizzate. Questo vi aiuterà ad evitare ogni potenziale errore dato
257 | dalla confusione della vostra funzione con una funzione nativa del CSS o di
258 | altre librerie.
259 |
260 | ```scss
261 | .selector-1 {
262 | @extend .other-rule;
263 | @include clearfix();
264 | @include box-sizing(border-box);
265 | width: x-grid-unit(1);
266 | // altre dichiarazioni
267 | }
268 | ```
269 |
270 |
271 |
272 | ## 5. Esempio pratico
273 |
274 | Un esempio di varie convenzioni.
275 |
276 | ```css
277 | /* ==========================================================================
278 | Layout a griglia
279 | ========================================================================== */
280 |
281 | /**
282 | * Layout a griglia con scroll orizzontale.
283 | *
284 | * Questo crea una singola riga di colonne, a piena altezza e che non vanno
285 | * a capo, che può essere navigata orizzontalmente all'interno del suo
286 | * contenitore.
287 | *
288 | * Esempio HTML:
289 | *
290 | *
291 | *
292 | *
293 | *
294 | *
295 | */
296 |
297 | /**
298 | * Contenitore griglia
299 | *
300 | * Deve contenere solo figli `.cell`.
301 | *
302 | * 1. Rimuove lo spazio tra le celle
303 | * 2. Previene che le celle inline-block vadano a capo
304 | */
305 |
306 | .grid {
307 | height: 100%;
308 | font-size: 0; /* 1 */
309 | white-space: nowrap; /* 2 */
310 | }
311 |
312 | /**
313 | * Celle della griglia
314 | *
315 | * Di default, nessuna larghezza esplicita. Estendible con le classi `.cell-n`.
316 | *
317 | * 1. Imposta la spaziatura tra le celle
318 | * 2. Ripristina il white-space ereditato da `.grid`
319 | * 3. Ripristina la dimensione del font ereditata da `.grid`
320 | */
321 |
322 | .cell {
323 | position: relative;
324 | display: inline-block;
325 | overflow: hidden;
326 | box-sizing: border-box;
327 | height: 100%;
328 | padding: 0 10px; /* 1 */
329 | border: 2px solid #333;
330 | vertical-align: top;
331 | white-space: normal; /* 2 */
332 | font-size: 16px; /* 3 */
333 | }
334 |
335 | /* Stati delle celle */
336 |
337 | .cell.is-animating {
338 | background-color: #fffdec;
339 | }
340 |
341 | /* Larghezza delle celle
342 | ========================================================================== */
343 |
344 | .cell-1 { width: 10%; }
345 | .cell-2 { width: 20%; }
346 | .cell-3 { width: 30%; }
347 | .cell-4 { width: 40%; }
348 | .cell-5 { width: 50%; }
349 |
350 | /* Modificatori di cella
351 | ========================================================================== */
352 |
353 | .cell--detail,
354 | .cell--important {
355 | border-width: 4px;
356 | }
357 | ```
358 |
359 |
360 |
361 | ## Ringraziamenti
362 |
363 | Grazie a tutti coloro che hanno fornito le traduzioni e contribuito a
364 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js). È stato una fonte di
365 | ispirazione, citazioni e linee guida.
366 |
367 |
368 |
369 | ## Licenza
370 |
371 | _Princìpi per la scrittura di CSS consistente ed idiomatico_ di Nicolas
372 | Gallagher è rilasciata sotto la [Creative Commons Attribution 3.0 Unported
373 | License](http://creativecommons.org/licenses/by/3.0/), che viene applicata
374 | anche a tutti i documenti e traduzioni contenuti in questo repository.
375 |
376 | Lavoro basato su
377 | [github.com/necolas/idiomatic-css](https://github.com/necolas/idiomatic-css).
378 |
--------------------------------------------------------------------------------
/translations/ja-JP/README.md:
--------------------------------------------------------------------------------
1 | # 一貫性のあるCSSらしいCSSを書くための原則
2 |
3 | 以下の文書はCSS開発のための合理的なスタイルガイドの骨子です。
4 | 規範になるべきものではないし、私自身のスタイルの好みを他者のコードに押し付けるつもりは一切ありません。しかし、これらのガイドラインは現存する一般的で分別のあるパターンを利用することを推奨します。
5 |
6 | このドキュメントは常に変わっていくものなので、新しいアイデアを常に求めています。ぜひアイデア等を投稿してください。
7 |
8 | [一貫性のあるCSSらしいCSSを書くための原則の英語版はこちらから](https://github.com/necolas/idiomatic-css/)
9 |
10 | ## 目次
11 |
12 | 1. [一般原則](#general-principles)
13 | 2. [ホワイトスペース(余白)](#whitespace)
14 | 3. [コメント](#comments)
15 | 4. [フォーマット](#format)
16 | 5. [命名規則](#naming)
17 | 6. [実例](#example)
18 | 7. [編成](#organization)
19 | 8. [ビルドとデプロイ](#build-and-deployment)
20 |
21 | [謝辞](#acknowledgements)
22 |
23 |
24 |
25 | ## 1. 一般原則
26 |
27 | > "成功を収めるプロジェクトをうまく管理することの一つが自分でコードを書いて実現する
28 | > ということではない。もし多くの人があなたのコードを利用しているなら、仕様の
29 | > 中にはあなたの好みではなく、最大限に明確なコードを書くべきである。" - Idan Gazit
30 |
31 | * どんなに多くの人が貢献したとしても、どのコードも一人で書いたようにする。
32 | * 同意の上のでのスタイルを厳格に守る。
33 | * もし悩むようであれば常に現存する共通のパターンを利用する。
34 |
35 |
36 |
37 | ## 2. ホワイトスペース(余白)
38 |
39 | プロジェクト内全てのソースコードで1つのスタイルのみを利用すること。ホワイトスペース(余白)は常に一貫性を保つこと。そしてホワイトスペース(余白)を可読性を向上するために利用すること。
40 |
41 | * インデントにはタブ、スペースを**絶対に**混在させないこと
42 | * ソフトインデント(スペース)かタブのどちらかを選び、その選択を途中で変更しないこと(スペースを優先)
43 | * もしスペースを利用する場合にインデントに利用する文字数を決めること (4スペースを優先)
44 |
45 | ヒント: 利用しているエディタにて“隠しキャラクターの表示”が出来る様に設定すること。これで行の最後のホワイトスペースを削除し、意図的ではない空行を削除し、無駄なコミットを避ける。
46 |
47 |
48 |
49 | ## 3. コメント
50 |
51 | ソースコード上の詳細なコメントは非常に重要です。コンポーネントがどのように動作するのか、どんな制約があるのか、そしてどんな構成になっているかを説明すること。チーム内の他のメンバーが一般的でなく、明確でもないコードの目的を推測させることがないようにしてください。
52 |
53 | コメントのスタイルはシンプルでかつソースコードベースの中で一貫性を保っている必要があります。
54 |
55 | * コメントは対象になるコンポーネントの上の行に配置すること。
56 | * コメントを宣言文の後に追加しないこと。
57 | * 折り返し行は分別のある最大行以内におさめること。例: 80文字
58 | * コメントを使ってCSSのコードを別々のセクションに分解すること。
59 | * コメントの文頭を大文字にし、テキストインデントに一貫性を持たせること。
60 |
61 | ヒント: エディタの設定でショートカットなどを用いて承諾済みのコメントパターンを出力できるようにしておく。
62 |
63 | #### CSSの例:
64 |
65 | ```css
66 | /* ==========================================================================
67 | セクションコメントブロック
68 | ========================================================================== */
69 |
70 | /* サブ・セクションコメントブロック
71 | ========================================================================== */
72 |
73 | /*
74 | * グループコメントブロック
75 | * 複数行になるドキュメントや説明の際に最適
76 | */
77 |
78 | /* 基本コメント */
79 | ```
80 |
81 | #### SCSSの例:
82 |
83 | ```scss
84 | // ==========================================================================
85 | // セクションコメントブロック
86 | // ==========================================================================
87 |
88 | // サブ・セクションコメントブロック
89 | // ==========================================================================
90 |
91 | //
92 | // グループコメントブロック
93 | // 複数行になるドキュメントや説明の際に最適
94 | //
95 |
96 | // 基本コメント
97 | ```
98 |
99 |
100 |
101 | ## 4. フォーマット
102 |
103 | 選択したコードフォーマットはコードが: 読みやすく、コメントが明確で、意図しないエラーを最低限に防ぎ、かつdiffやblameなどのコマンドの利点が活かせる形であること。
104 |
105 | 1. 複数セレクタを持つルールセットの場合、セレクタを1行ずつ記述すること。
106 | 2. ルールセットの開き中カッコの前に1スペースを入れること。
107 | 3. 宣言ブロックないでは宣言を1行ずつ記述すること。
108 | 4. 各宣言で1レベルのインデントを行うこと。
109 | 5. 宣言文のコロンの後にに1スペースを入れること。
110 | 6. 宣言ブロック内の最後の宣言文には常にセミコロンを追加すること。
111 | 7. ルールセットの閉じ中括弧はルールセット内の1番始めの文字の位置に合わせること。
112 | 8. ルールセットは空行で分けること。
113 |
114 | ```css
115 | .selector-1,
116 | .selector-2,
117 | .selector-3 {
118 | -webkit-box-sizing: border-box;
119 | -moz-box-sizing: border-box;
120 | box-sizing: border-box;
121 | display: block;
122 | color: #333;
123 | background: #fff;
124 | }
125 | ```
126 |
127 | #### 宣言順
128 |
129 | 宣言の順番は1つの原則に従って並べること。私の場合は関連するプロパティ同士でグループ化し、構造的に重要なプロパティ(例: ポジションやボックスモデル)はタイポグラフィー、バックグランド、カラーのプロパティよりも前に宣言するようにしている。
130 |
131 | ```css
132 | .selector {
133 | position: relative;
134 | display: block;
135 | width: 50%;
136 | height: 100px;
137 | padding: 10px;
138 | border: 0;
139 | margin: 10px;
140 | color: #fff
141 | background: #000;
142 | }
143 | ```
144 |
145 | アルファベット順もよく使われるが欠点は関連するプロパティ同士を分断してしまう点。例えば、ポジションのオフセットをグループ化できないし、ボックスモデルのプロパティは宣言ブロック内でバラバラに宣言されることになってしまいます。
146 |
147 | #### 例外と少しの偏差
148 |
149 | 1行の宣言が数多くある場合、これまでと異なる1行フォーマットを利用することも可能です。この場合、中カッコの内側両端に1つのスペースを入れること。
150 |
151 | ```css
152 | .selector-1 { width: 10%; }
153 | .selector-2 { width: 20%; }
154 | .selector-3 { width: 30%; }
155 | ```
156 |
157 | グラデーションやシャドウなどの長く、コンマで分割できるプロパティ値を持つ場合、diffをより有効活用するために複数ラインを利用しても構いません。様々なフォーマットが考えられますが、以下はその内の1つです。
158 |
159 | ```css
160 | .selector {
161 | box-shadow:
162 | 1px 1px 1px #000,
163 | 2px 2px 1px 1px #ccc inset;
164 | background-image:
165 | linear-gradient(#fff, #ccc),
166 | linear-gradient(#f3c, #4ec);
167 | }
168 | ```
169 |
170 | #### その他
171 |
172 | * hex値は小文字を利用すること。例: `#aaa`
173 | * シングル、ダブルクォートには一貫性を持つこと。推奨はダブルクォートです。例: `content: ""`
174 | * セレクタ内の属性値は常にクォートで囲むこと。例: `input[type="checkbox"]`
175 | * **可能な場合**にはゼロになる値に対して単位指定を行わないこと。例: `margin: 0`
176 |
177 | ### プリプロセッサ: 追加フォーマット
178 |
179 | CSSプリプロセッサの特性、機能、シンタックスはツールによって全く異なります。規則は利用しているプリプロセッサの特性に併せて拡張してください。
180 | 以下のガイドラインはSassを対象としたものになります。
181 |
182 | * 入れ子は1レベルに止めること。2レベル以上の入れ子構造になる場合は再度コードを見直すこと。これによりCSSのセレクタが必要以上に詳細になるのを防ぎます。
183 | * 入れ子ルールを数多く利用しないこと。読みやすさに影響を与え始めるようであれば分割すること。入れ子ルール内に20以上のルールセットを置かないことを推奨します。
184 | * `@extend`文は宣言ブロック内の1番上に記述すること。
185 | * 可能な限り`@include`を宣言ブロック内、`@extend`の下にグループ化すること
186 | * ネイティブCSSの機能とカスタムした機能との違いの混乱を避け、ライブラリからの関数との衝突を避けるためにカスタム関数に`x-`のようなプリフィックスを利用するか他のネームスペースをつけるようにすること。
187 |
188 | ```scss
189 | .selector-1 {
190 | @extend .other-rule;
191 | @include clearfix();
192 | @include box-sizing(border-box);
193 | width: x-grid-unit(1);
194 | // other declarations
195 | }
196 | ```
197 |
198 |
199 |
200 | ## 5. 命名規則
201 |
202 | 我々は人間コードコンパイラ、コンプレッサではないので、そのように振る舞う必要はありません。
203 |
204 | HTMLのクラスは明確で熟慮された名前を使用すること。HTMLファイル、CSSファイル内の両方で理解しやすく、一貫性のある命名パターンを選ぶこと。
205 |
206 | ```css
207 | /* 悪い命名規則の例 */
208 |
209 | .s-scr {
210 | overflow: auto;
211 | }
212 |
213 | .cb {
214 | background: #000;
215 | }
216 |
217 | /* よりよい命名規則の例 */
218 |
219 | .is-scrollable {
220 | overflow: auto;
221 | }
222 |
223 | .column-body {
224 | background: #000;
225 | }
226 | ```
227 |
228 |
229 |
230 | ## 6. 実例
231 |
232 | 様々な規則の例
233 |
234 | ```css
235 | /* ==========================================================================
236 | グリッドレイアウト
237 | ========================================================================== */
238 |
239 | /*
240 | * HTML例:
241 | *
242 | *
246 | */
247 |
248 | .grid {
249 | overflow: visible;
250 | height: 100%;
251 | /* Prevent inline-block cells wrapping */
252 | white-space: nowrap;
253 | /* Remove inter-cell whitespace */
254 | font-size: 0;
255 | }
256 |
257 | .cell {
258 | box-sizing: border-box;
259 | position: relative;
260 | overflow: hidden;
261 | width: 20%;
262 | height: 100%;
263 | /* Set the inter-cell spacing */
264 | padding: 0 10px;
265 | border: 2px solid #333;
266 | vertical-align: top;
267 | /* Reset white-space */
268 | white-space: normal;
269 | /* Reset font-size */
270 | font-size: 16px;
271 | }
272 |
273 | /* Cellの状態 */
274 |
275 | .cell.is-animating {
276 | background-color: #fffdec;
277 | }
278 |
279 | /* Cellのサイズ
280 | ========================================================================== */
281 |
282 | .cell-1 { width: 10%; }
283 | .cell-2 { width: 20%; }
284 | .cell-3 { width: 30%; }
285 | .cell-4 { width: 40%; }
286 | .cell-5 { width: 50%; }
287 |
288 | /* Cellの修飾因子
289 | ========================================================================== */
290 |
291 | .cell--detail,
292 | .cell--important {
293 | border-width: 4px;
294 | }
295 | ```
296 |
297 |
298 |
299 | ## 7. 編成
300 |
301 | ソースコードの編成はどんなCSSコード内でも重要なパートになり、また巨大なコードベースの場合はさらに重要になります。
302 |
303 | * ソースコードは論理的にはっきり異なることがわかるように分割すること
304 | * コンポーネントの明白さを強めるために別ファイルにすること(ビルドステップで連結すること)
305 | * プリプロセッサを利用している場合、共通なコード、タイポグラフィー、色などを変数にしておくこと
306 |
307 |
308 |
309 | ## 8. ビルドとデプロイ
310 |
311 | プロジェクトは常にソースコードの文法チェック、テスト、圧縮、プロダクションへの準備のためのバージョンコントロールの手法を持つべきです。
312 | これらのタスクにはBen Alman氏による[grunt](https://github.com/cowboy/grunt)が優れたツールです。
313 |
314 |
315 |
316 | ## 謝辞
317 |
318 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js)に貢献した皆さんに感謝します。idoomatic.jsはインスピレーションであり、引用もし、ガイドラインとしても活用しました。
319 |
--------------------------------------------------------------------------------
/translations/ko-KR/README.md:
--------------------------------------------------------------------------------
1 | # 일관성있는 CSS다운 CSS를 작성하기 위한 원칙
2 |
3 | 이하 문서는 CSS개발을 위한 합리적인 스타일가이드의 중요한 내용입니다.
4 | 규범이 될만한 것이라 하긴 좀 그렇고 스스로 스타일 작업시 즐겨쓰는 방식을 다른분들께 꼭 이렇게 해야 한다고 말하려는 의도는 전혀 없습니다. 단, 이런 가이드라인은 현존하는 일반적이며 분별력있는 페턴을 이용하는 것을 추천합니다.
5 |
6 | 이 문서는 계속 변경해 나갈 예정이므로 새로운 아이디어를 계속해서 추가해 나갈 생각입니다. 많은 아이디어들을 주시면 고맙겠습니다.
7 |
8 | [일관성있는 CSS다운 CSS를 작성하기 위한 원칙](https://github.com/necolas/idiomatic-css/)
9 |
10 |
11 | ## 목차
12 |
13 | 1. [일반원칙](#general-principles)
14 | 2. [화이트스페이스(여백)](#whitespace)
15 | 3. [커맨트(주석)](#comments)
16 | 4. [포멧](#format)
17 | 5. [명명규칙](#naming)
18 | 6. [실례](#example)
19 | 7. [편성](#organization)
20 | 8. [빌드와 디플로이](#build-and-deployment)
21 |
22 | [감사의 말](#acknowledgements)
23 |
24 |
25 |
26 | ## 1. 일반규칙
27 |
28 | > "성공을 거둔 프로젝트를 잘 관리하는 한 방법은 스스로 코드를 작성하여 실행해 보는것이다.
29 | > 라고 말하는건 아니다. 혹시 많은 사람들이 당신의 코드를 이용하고 있다면, 사양은
30 | > 당신의 취향이 아닌, 최대한 명확한 코드를 사용해야 한다." - Idan Gazit
31 |
32 | * 아무리 많은 사람들이 참여했다고 하더라도, 코드는 한사람이 작성한 것처럼 보여야 한다.
33 | * 동의하에 스타일을 엄격하게 지킨다.
34 | * 혹시 고민하게 될 경우에는 현존하는 공통의 페턴을 이용한다.
35 |
36 |
37 |
38 | ## 2. 화이트스페이스(여백)
39 |
40 | 프로젝트의 모든 소스코드에 한개의 스타일만을 사용할것. 화이트스페이스(여백)은 늘 일관성을 갖어야 한다. 그리고 화이트스페이스(여백)을 가독성을 향상시키기 위해서 이용해야 한다.
41 |
42 | * 들여쓰기는 텝, 스페이스를 **절대로** 섞어서 사용해서는 안된다.
43 | * 들여쓰기는 스페이스로 할지 아니면 텝으로 할지를 결정하고, 도중에 변경해서는 안된다.(스페이스 선호)
44 | * 만약 스페이스를 이용하는 경우에 들여쓰기에 이용하는 문자수를 결정할 것.(4 스페이스 선호)
45 |
46 | 힌트: 이용하고 있는 에디터에 숨김문자표시기능을 활성화 해두자. 이걸로 행의 마지막에 스페이스를 삭제한다던가 불필요한 공백을 삭제하여 불필요한 커밋을 피할 수 있다.
47 |
48 |
49 |
50 | ## 3. 커맨트(주석)
51 |
52 | 소스코드에 상세한 주석은 비상시에 중요하다. 컴포넌트가 어떤식으로 동작하는 건지, 어떤 제약이 있는지, 어떤 구성을 갖고 있는지를 설명할 수 있기 때문이다. 팀 내에서 다른 맴버가 일반적이지 않고 명확하지도 않은 코드를 추측하게끔 하는 일은 만들어서는 안된다.
53 |
54 | 주석의 스타일은 간단하고 소스코드안에서 일관성을 갖고 있을 필요가 있다.
55 |
56 | * 주석은 대상이 되는 컴포넌트의 상단에 배치한다.
57 | * 주석은 선언문의 뒤에 추가하지 않도록 한다.
58 | * 행바꿈 折り返し行は分別のある最大行以内におさめること。例: 80文字
59 | * 주석을 사용해서 CSS 코드를 따로따로 구분하기.
60 | * 주석의 맨 앞자는 대문자로 하고 텍스트의 들여넣기는 일관성을 갖도록 한다.
61 |
62 | 힌트: 에디터의 설정에 스닙펫기능을 활용해서 정해진 주석페턴을 등록해놓고 사용하도록 한자.
63 |
64 | #### CSS의 예:
65 |
66 | ```css
67 | /* ==========================================================================
68 | 섹션 블럭
69 | ========================================================================== */
70 |
71 | /* 서브 섹션 블럭
72 | ========================================================================== */
73 |
74 | /*
75 | * 그룹 블럭
76 | * 여러행을 포함하고 있는 문서나 설명을 적을때 사용한다.
77 | */
78 |
79 | /* 기본 주석 */
80 | ```
81 |
82 | #### SCSS의 예:
83 |
84 | ```scss
85 | // ==========================================================================
86 | // 색션 블럭
87 | // ==========================================================================
88 |
89 | // 서브 섹션 블럭
90 | // ==========================================================================
91 |
92 | //
93 | // 그룹 블럭
94 | // 여러행을 포함하고 있는 문서나 설명을 적을때 사용한다.
95 | //
96 |
97 | // 기본 주석
98 | ```
99 |
100 |
101 |
102 | ## 4. 포멧
103 |
104 | 선택한 코드 포멧은 코드가 해독이 쉬운지, 주석이 명확한지, 예상치 못한 에러를 최대한 방지하고 있는지, 그리고 diff,blame과 같은 커멘드의 이점을 잘 활용하는 형태여야 한다.
105 |
106 | 1. 복수셀렉터를 갖고있는 룰셋의 경우, 셀러터를 한줄씩 기술할것.
107 | 2. 룰셋에서 맨 처음 괄호의 앞에 스페이스 한개를 둘것.
108 | 3. 선언 블럭 안에서는 선언을 한줄씩 기술할것.
109 | 4. 각 선언에 1레벨의 들여쓰기를 할것.
110 | 5. 선언문의 콜론뒤에 스페이스 한개를 둘것.
111 | 6. 선언 블럭안의 맨 마지막의 선언문에는 늘 세미콜론을 추가할 것.
112 | 7. 룰셋의 닫기괄호는 룰셋안의 첫번째 문자의 위치와 맞춘다.
113 | 8. 룰셋은 빈줄로 구분을 짓는다.
114 |
115 | ```css
116 | .selector-1,
117 | .selector-2,
118 | .selector-3 {
119 | -webkit-box-sizing: border-box;
120 | -moz-box-sizing: border-box;
121 | box-sizing: border-box;
122 | display: block;
123 | color: #333;
124 | background: #fff;
125 | }
126 | ```
127 |
128 | #### 선언
129 |
130 | 선언 순서는 단 하나의 원칙에 따라서만 작성할 것. 저와 같은 경우엔 관련하는 프로퍼티끼리 그룹화하였고, 구조적으로 중요한 프로퍼티(예:포지션이나 박스모델)는 타이포그래피, 백그라운드, 컬러의 프로퍼티보다 먼저 선언하도록 하고 있습니다.
131 |
132 |
133 | ```css
134 | .selector {
135 | position: relative;
136 | display: block;
137 | width: 50%;
138 | height: 100px;
139 | padding: 10px;
140 | border: 0;
141 | margin: 10px;
142 | color: #fff
143 | background: #000;
144 | }
145 | ```
146 |
147 | 알파벳순도 자주 사용되고 있지만 결점은 관련하는 프로퍼티끼리 떨어져있다는 점입니다. 예를 들어서 포지션의 옵셋을 그룹화할수가 없고, 박스모델의 프로퍼티는 선언블럭안에서 서로서로 떨어져서 선언 됩니다.
148 |
149 | #### 예외와 작은 편차
150 |
151 | 한줄 선언의 수가 많아지게 되는 경우, 지금까지와는 다른 한줄포멧을 사용할 수 있습니다. 이 경우에는 중괄호 안쪽의 양쪽 끝에 스페이스를 한자 넣는 것입니다.
152 |
153 | ```css
154 | .selector-1 { width: 10%; }
155 | .selector-2 { width: 20%; }
156 | .selector-3 { width: 30%; }
157 | ```
158 |
159 | 그라데이션이나 쉐도우같이 길고, 컴마로 구분하여 사용하는 프로퍼티값을 갖고있는 경우에는 diff를 좀 더 유용하게 활용하기 위해 여러줄을 사용해도 괜찮습니다. 여러가지의 포맷이 있을 것으로 생각되지만 밑에 적은것과 비슷한 형태일 것입니다.
160 |
161 | ```css
162 | .selector {
163 | box-shadow:
164 | 1px 1px 1px #000,
165 | 2px 2px 1px 1px #ccc inset;
166 | background-image:
167 | linear-gradient(#fff, #ccc),
168 | linear-gradient(#f3c, #4ec);
169 | }
170 | ```
171 |
172 | #### 그 외...
173 |
174 | * hex값은 소문자를 이용할 것. 예: `#aaa`
175 | * 싱글따옴표, 더블따옴표에는 일관성을 둘 것. 추천하는 것은 더블따옴표입니다. 예: `content: ""`
176 | * 셀렉터안의 속성치는 늘 따옴표로 감쌀 것. 예: `input[type="checkbox"]`
177 | * **가능한 경우**에는 0이 되는 값에는 단위지정을 하지 않는다. 例: `margin: 0`
178 |
179 | ### 프리프로세서:추가 포멧
180 |
181 | CSS프리프로세서의 특성, 기능, 신텍스는 툴에 의해서 전혀 틀립니다. 규칙은 이용하고 있는 프리프로세서의 특성에 맞춰서 확장하세요.
182 | 이후의 가이드라인은 SASS를 대상으로 하고 있습니다.
183 |
184 | * 코드블럭(nesting)은 한단계만 들여쓰도록 한다. 2단계이상 들어간 중첩요소들이 있는 구조라면 다시한번 코드를 고쳐야 한다. 이렇게 함으로써 CSS셀렉터가 필요이상 상세해 지는걸 막을 수 있다.
185 | * 코드블럭 작성룰은 여러가지를 사용하지 않도록 한다. 읽기 어려워 질것 같다면 나눠서 작성한다. 코드블럭에는 20개 이상의 룰셋을 두지 않도록 한는걸 추천한다.
186 | * `@extend`문은 선언 블럭의 최상단에 기술한다.
187 | * 가능한한 `@include`는 선언블럭안의 `@extend`의 밑에 그룹화 한다.
188 | * 네이티브 CSS함수와 커스텀화한 함수의 차이를 알기 쉽게 하고, 라이브러리에서 함수의 충돌을 피하기 위해 커스텀화한 함수의 접두어로 'x-'를 사용한다던가 아니면 다른 네임스페이스를 지정하여 사용하도록 한다.
189 |
190 | ```scss
191 | .selector-1 {
192 | @extend .other-rule;
193 | @include clearfix();
194 | @include box-sizing(border-box);
195 | width: x-grid-unit(1);
196 | // other declarations
197 | }
198 | ```
199 |
200 |
201 |
202 | ## 5. 명명규칙
203 |
204 | 우리 인간은 코드컴파일러, 콤프레셔가 아니기 때문에 그렇게 행동할 필요는 없다.
205 |
206 | HTML 클래스는 명확하고 심사숙고하여 만든 이름을 사용하여야 한다. HTML화일, CSS화일 안에서 서로가 알기 쉽도록, 일관성있는 명명 페턴을 선택해야 한다.
207 |
208 | ```css
209 | /* 안좋은 명명규칙의 예 */
210 |
211 | .s-scr {
212 | overflow: auto;
213 | }
214 |
215 | .cb {
216 | background: #000;
217 | }
218 |
219 | /* 좀 더 낳은 명명규칙의 예 */
220 |
221 | .is-scrollable {
222 | overflow: auto;
223 | }
224 |
225 | .column-body {
226 | background: #000;
227 | }
228 | ```
229 |
230 |
231 |
232 | ## 6. 실례
233 |
234 | 여러가지 규칙의 예
235 |
236 | ```css
237 | /* ==========================================================================
238 | 그리드 레이아웃
239 | ========================================================================== */
240 |
241 | /*
242 | * HTML예:
243 | *
244 | *
248 | */
249 |
250 | .grid {
251 | overflow: visible;
252 | height: 100%;
253 | /* Prevent inline-block cells wrapping */
254 | white-space: nowrap;
255 | /* Remove inter-cell whitespace */
256 | font-size: 0;
257 | }
258 |
259 | .cell {
260 | box-sizing: border-box;
261 | position: relative;
262 | overflow: hidden;
263 | width: 20%;
264 | height: 100%;
265 | /* Set the inter-cell spacing */
266 | padding: 0 10px;
267 | border: 2px solid #333;
268 | vertical-align: top;
269 | /* Reset white-space */
270 | white-space: normal;
271 | /* Reset font-size */
272 | font-size: 16px;
273 | }
274 |
275 | /* Cell 상태 */
276 |
277 | .cell.is-animating {
278 | background-color: #fffdec;
279 | }
280 |
281 | /* Cell 사이즈
282 | ========================================================================== */
283 |
284 | .cell-1 { width: 10%; }
285 | .cell-2 { width: 20%; }
286 | .cell-3 { width: 30%; }
287 | .cell-4 { width: 40%; }
288 | .cell-5 { width: 50%; }
289 |
290 | /* Cell 수식 인자
291 | ========================================================================== */
292 |
293 | .cell--detail,
294 | .cell--important {
295 | border-width: 4px;
296 | }
297 | ```
298 |
299 |
300 |
301 | ## 7. 편성
302 |
303 | 소스코드의 편성은 어떤 CSS코드안에서도 중요한 부분이며 또한 거대한 코드베이스의 경우에는 더더욱 중요해진다.
304 |
305 | * 소스코드는 논리적으로 확실하게 틀린부분을 이해할 수 있도록 잘 나눠놔야 한다.
306 | * 컴포넌트의 명백함을 강화시키기 위해서 별도의 화일로 만든다.(빌드스텝에서 연결한다.)
307 | * 프리프로세서를 이용하는 경우에는 공통의 코드, 타이포그래피, 색등을 변수로 정의 해둔다.
308 |
309 |
310 |
311 | ## 8. 빌드와 디플로이
312 |
313 | 프로젝트는 늘 소스코드의 문법체크, 테스트, 압축과 실제 사용에 앞서 버젼관리의 수단들을 갖추어야 합니다.
314 | 이런 테스크들은 Ben Alman씨에 의해서 만들어진 [grunt](https://github.com/cowboy/grunt)가 괜찮은 툴입니다.
315 |
316 |
317 |
318 | ## 감사의 말
319 |
320 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js)에 참여해주신 여러분들께 감사드립니다. idiomatic.js는 기발한 생각이며、인용과 가이드라인의 원본입니다.
321 |
--------------------------------------------------------------------------------
/translations/nl-NL/README.md:
--------------------------------------------------------------------------------
1 | # Principes voor het schrijven van consistente, idiomatische CSS
2 |
3 | Het volgende document schetst een logische stijlgids voor het schrijven van
4 | CSS. Het is niet normatief bedoeld en ik wens niet mijn stijlvoorkeuren op te
5 | dringen aan andermans code. Deze richtlijnen zijn echter een sterke
6 | aanmoediging voor het gebruik van bestaande, algemene, verstandige patronen.
7 |
8 | Dit is een document in ontwikkeling en nieuwe ideeën zijn altijd welkom. Draag
9 | alstublieft bij!
10 |
11 | Andere vertalingen zijn te vinden in het [originele Engelse Idiomatic CSS
12 | document](https://github.com/necolas/idiomatic-css).
13 |
14 |
15 | ## Inhoudsopgave
16 |
17 | 1. [Algemene principes](#general-principles)
18 | 2. [Witruimte](#whitespace)
19 | 3. [Commentaar](#comments)
20 | 4. [Opmaak](#format)
21 | 5. [Naamgeving](#naming)
22 | 6. [Praktisch voorbeeld](#example)
23 | 7. [Ordening](#organization)
24 | 8. [Build en deployment](#build-and-deployment)
25 |
26 | [Dank](#acknowledgements)
27 |
28 |
29 |
30 | ## 1. Algemene principes
31 |
32 | > "Het zijn van een goed rentmeester van een succesvol project is deels het
33 | > realiseren dat het schrijven van code voor jezelf een Slecht Idee™ is. Als
34 | > duizenden mensen je code gebruiken schrijf je code dan voor maximale
35 | > duidelijkheid, niet je persoonlijke voorkeur slim om te gaan binnen de
36 | > specificatie." - Idan Gazit
37 |
38 | * Alle code in elke codebase zou getypt moeten lijken door een enkel persoon,
39 | ongeacht hoeveel personen een bijdrage leverden.
40 | * Dwing de afgesproken stijl streng af.
41 | * Gebruik bij twijfel bestaande, algemene patronen.
42 |
43 |
44 |
45 | ## 2. Witruimte
46 |
47 | In de hele broncode van uw project zou slechts één stijl moeten bestaan. Wees
48 | altijd consistent in het gebruik van witruimte. Gebruik witruimte om de
49 | leesbaarheid te bevorderen.
50 |
51 | * Wissel _nooit_ het gebruik van tabs en spaties voor het inspringen van tekst
52 | af.
53 | * Kies tussen zacht inspringen (spaties) of echte tabs. En blijf daarbij
54 | (voorkeur: spaties).
55 | * Als u spaties gebruikt, kies het aantal karakters per niveau van inspringen
56 | (voorkeur: 4 spaties)
57 |
58 | Tip: Stel uw tekstverwerker in om "onzichtbare tekens te tonen". Dit stelt u in
59 | staat witruimte aan regeleinden en onbedoelde witregels te verwijderen en
60 | voorkomt vervuilde commits.
61 |
62 |
63 |
64 | ## 3. Commentaar
65 |
66 | Goed becommentarieerde code is extreem belangrijk. Neem de tijd om componenten
67 | te beschrijven. Hoe deze werken, de beperkingen en de manier waarom deze zijn
68 | samengesteld. Laat anderen in het team niet raden naar het doel van ongewone of
69 | onduidelijke code.
70 |
71 | De stijl van commentaar binnen broncode zou simpel en consistent moeten zijn.
72 |
73 | * Plaats commentaar op een nieuwe regel boven het onderwerp.
74 | * Vermijd commentaar aan het einde van een regel.
75 | * Houdt regellengte tot een verstandig maximum: b.v. 80 kolommen.
76 | * Maak ruim gebruik van commentaar om CSS-code op te breken in aparte
77 | secties.
78 | * Gebruik "standaard kapitalen"-commentaar en het consistent inspringen van
79 | tekst.
80 |
81 | Tip: Stel uw tekstverwerker in met toetscombinaties om de afgesproken algemene
82 | patronen te genereren.
83 |
84 |
85 | #### CSS-voorbeeld:
86 |
87 | ```css
88 | /* ==========================================================================
89 | Sectie commentaarblok
90 | ========================================================================== */
91 |
92 | /* Subsectie commentaarblok
93 | ========================================================================== */
94 |
95 | /*
96 | * Groep commentaarblok.
97 | * Ideaal voor uitleg over meerdere regels en documentatie.
98 | */
99 |
100 | /* Standaard commentaar */
101 | ```
102 |
103 | #### SCSS-voorbeeld:
104 |
105 | ```scss
106 | // ==========================================================================
107 | // Sectie commentaarblok
108 | // ==========================================================================
109 |
110 | // Subsectie commentaarblok
111 | // ==========================================================================
112 |
113 | //
114 | // Groep commentaarblok
115 | // Ideaal voor uitleg over meerdere regels en documentatie.
116 | //
117 |
118 | // Standaard commentaar
119 | ```
120 |
121 |
122 |
123 | ## 4. Opmaak
124 |
125 | De gekozen code-opmaak moet verzekeren dat de code: makkelijk te lezen en te
126 | becommentariëren is. Dit vermindert de kans op de onbedoelde introductie van
127 | fouten en resulteert in bruikbare diffs en blames.
128 |
129 | 1. Eén aparte selector per regel en in multi-selector rulesets.
130 | 2. Eén afzonderlijke spatie voor de openings-accolade van een ruleset.
131 | 3. Eén declaratie per regel in een declaratieblok.
132 | 4. Eén inspringniveau voor elke declaratie.
133 | 5. Eén afzonderlijke spatie na de dubbele punt van een declaratie.
134 | 6. Voeg altijd een puntkomma aan het eind van de laatste declaratie in een
135 | declaratieblok.
136 | 7. Plaats de afsluitende accolade van een ruleset in dezelfde kolom als het
137 | eerste karakter van de ruleset.
138 | 8. Scheidt elke ruleset door een witregel.
139 |
140 | ```css
141 | .selector-1,
142 | .selector-2,
143 | .selector-3 {
144 | -webkit-box-sizing: border-box;
145 | -moz-box-sizing: border-box;
146 | box-sizing: border-box;
147 | display: blok;
148 | color: #333;
149 | background: #fff;
150 | }
151 | ```
152 |
153 | #### Volgorde van declaraties
154 |
155 | Declaraties dienen geordend te worden overeenkomstig een enkel principe. Mijn
156 | voorkeur is dat gerelateerde eigenschappen gegroepeerd worden en dat
157 | structureel belangrijke eigenschappen (b.v. positionering en box-model) voor
158 | typografische-, achtergronds- en kleureigenschappen gedeclareerd worden.
159 |
160 | ```css
161 | .selector {
162 | position: relative;
163 | display: blok;
164 | width: 50%;
165 | height: 100px;
166 | padding: 10px;
167 | border: 0;
168 | margin: 10px;
169 | color: #fff
170 | background: #000;
171 | }
172 | ```
173 |
174 | Alfabetische volgorde is ook populair, maar het nadeel is dat dit gerelateerde
175 | eigenschappen afzondert. Bijvoorbeeld: positie-afstanden zijn niet langer
176 | gegroepeerd en box-modeleigenschappen kunnen door het hele declaratieblok
177 | verspreid worden.
178 |
179 | #### Uitzonderingen en kleine afwijkingen
180 |
181 | Grote blokken alleenstaande declaraties kunnen een enigszins andere,
182 | enkele-regel-opmaak gebruiken. In dit geval zou een spatie toegevoegd kunnen
183 | worden na de openingsaccolade en voor de sluitende accolade.
184 |
185 | ```css
186 | .selector-1 { width: 10%; }
187 | .selector-2 { width: 20%; }
188 | .selector-3 { width: 30%; }
189 | ```
190 |
191 | Lange, kommagescheiden eigenschapwaarden - zoals sets aan verlopen of schaduwen
192 | - kunnen gerangschikt kunnen worden over meerdere regels om de leesbaarheid en
193 | beter bruikbare diffs te bevorderen. Er zijn verschillende opmaakstijlen die
194 | gebruikt zouden kunnen worden; een voorbeeld is hieronder getoond.
195 |
196 | ```css
197 | .selector {
198 | box-shadow:
199 | 1px 1px 1px #000,
200 | 2px 2px 1px 1px #ccc inset;
201 | background-image:
202 | linear-gradient(#fff, #ccc),
203 | linear-gradient(#f3c, #4ec);
204 | }
205 | ```
206 |
207 | #### Diversen
208 |
209 | * Gebruik onderkast hex waarden, b.v., `#aaa`.
210 | * Gebruik consistent enkele of dubbele aanhalingstekens. Dubbele
211 | aanhalingstekens hebben de voorkeur, b.v. `content: ""`.
212 | * Gebruik altijd aanhalingstekens bij attribuutwaarden in selectors, b.v.
213 | `input[type="checkbox"]`.
214 | * Vermijd, _indien toegestaan_, specifieke eenheden voor nulwaarden b.v.
215 | `margin: 0`.
216 |
217 | ### Preprocessors: extra opmaakoverwegingen
218 |
219 | Verschillende CSS preprocessors hebben verschillende kenmerken, functionaliteit
220 | en syntaxis. Uw conventies zullen moeten worden afgestemd op de unieke
221 | kenmerken van de gebruikte preprocessors. De volgende richtlijnen hebben
222 | betrekking op Sass.
223 |
224 | * Beperk geneste regels tot 1 niveau diep. Bekijk sets dieper dan 2 niveaus
225 | opnieuw. Dit voorkomt te specifieke CSS-selectors.
226 | * Voorkom grote aantallen geneste regels. Splits ze wanneer de leesbaarheid
227 | verminderd. De voorkeur is om geneste regels van meer dan 20 regels te
228 | vermijden.
229 | * Plaats `@extend`-statements altijd op de eerste regel van een
230 | declaratieblok.
231 | * Groepeer `@include`-statements waar mogelijk bovenaan een declaratieblok, na
232 | mogelijke `@extend`-statements.
233 | * Overweeg een voorvoegsel van `x-` of een andere namespace voor eigen
234 | functies. Dit voorkomt mogelijke verwarring van uw functies met een CSS-eigen
235 | functie of een conflict met functies van andere libraries.
236 |
237 | ```scss
238 | .selector-1 {
239 | @extend .other-rule;
240 | @include clearfix();
241 | @include box-sizing(border-box);
242 | width: x-grid-unit(1);
243 | // andere declaraties
244 | }
245 | ```
246 |
247 |
248 |
249 | ## 5. Naamgeving
250 |
251 | U bent geen menselijke codecompiler/compressor; probeer dit dan ook niet te
252 | zijn.
253 |
254 | Gebruik duidelijke en doordachte namen voor HTML classes. Kies een begrijpelijk
255 | en consistent patroon voor naamgeving dat zowel in de HTML- als CSS-bestanden
256 | voor zich spreekt.
257 |
258 | ```css
259 | /* voorbeeld van code met slechte naamgeving */
260 |
261 | .s-scr {
262 | overflow: auto;
263 | }
264 |
265 | .cb {
266 | background: #000;
267 | }
268 |
269 | /* Voorbeeld van code met betere naamgeving */
270 |
271 | .is-scrollable {
272 | overflow: auto;
273 | }
274 |
275 | .column-body {
276 | background: #000;
277 | }
278 | ```
279 |
280 |
281 |
282 | ## 6. Praktisch voorbeeld
283 |
284 | Een voorbeeld van verschillende conventies.
285 |
286 | ```css
287 | /* ==========================================================================
288 | Grid lay-out
289 | ========================================================================== */
290 |
291 | /*
292 | * Voorbeeld HTML:
293 | *
294 | *
298 | */
299 |
300 | .grid {
301 | overflow: visible;
302 | height: 100%;
303 | /* Voorkom het omslaan van inline-block cellen */
304 | white-space: nowrap;
305 | /* Verwijder witruimte tussen cellen */
306 | font-size: 0;
307 | }
308 |
309 | .cell {
310 | box-sizing: border-box;
311 | position: relative;
312 | overflow: hidden;
313 | width: 20%;
314 | height: 100%;
315 | /* Bepaal de ruimte tussen cellen */
316 | padding: 0 10px;
317 | border: 2px solid #333;
318 | vertical-align: top;
319 | /* Herstel witruimte */
320 | white-space: normal;
321 | /* Herstel font-size */
322 | font-size: 16px;
323 | }
324 |
325 | /* Cel states */
326 |
327 | .cell.is-animating {
328 | background-color: #fffdec;
329 | }
330 |
331 | /* Celafmetingen
332 | ========================================================================== */
333 |
334 | .cell-1 { width: 10%; }
335 | .cell-2 { width: 20%; }
336 | .cell-3 { width: 30%; }
337 | .cell-4 { width: 40%; }
338 | .cell-5 { width: 50%; }
339 |
340 | /* Celaanpassingen
341 | ========================================================================== */
342 |
343 | .cell--detail,
344 | .cell--important {
345 | border-width: 4px;
346 | }
347 | ```
348 |
349 |
350 |
351 | ## 7. Ordening
352 |
353 | Code-organisatie is een belangrijk onderdeel van elke CSS codebase en cruciaal
354 | voor grotere codebases.
355 |
356 | * Verdeel logisch afzonderlijke codeonderdelen.
357 | * Gebruik afzonderlijke bestanden (samengevoegd door een buildproces) om code
358 | voor aparte componenten op te breken.
359 | * Abstraheer algemene code in variabelen voor kleur, typografie enz. als
360 | gebruik gemaakt wordt van een preprocessor.
361 |
362 |
363 |
364 | ## 8. Build en deployment
365 |
366 | Projecten dienen altijd een generieke manier te bevatten om broncode te linten,
367 | testen, comprimeren en van versienummer te voorzien in voorbereiding op gebruik
368 | in productie. [grunt](https://github.com/cowboy/grunt) door Ben Alman is
369 | hiervoor een uitstekende oplossing.
370 |
371 |
372 | ## Dank
373 |
374 | Dank voor iedereen die bijgedragen heeft aan
375 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js). Het was een bron van
376 | inspiratie, citaties en richtlijnen.
377 |
--------------------------------------------------------------------------------
/translations/pl-PL/README.md:
--------------------------------------------------------------------------------
1 | # Zasady tworzenia spójnych, zgodnych z regułami języka deklaracji CSS
2 |
3 | Poniżej opisane zostały podstawowe zasady tworzenia arkuszy stylów. Nie jest
4 | to uniwersalne czy wyczerpujące temat zestawienie. Intencją autora nie było
5 | bowiem narzucanie jedynie słusznych rozwiązań, a raczej zachęta do stosowania
6 | istniejących, wypróbowanych i uznanych wzorców.
7 |
8 | Z tego samego powodu mile widziana będzie wszelka pomoc w dalszym rozwijaniu i
9 | wzbogacaniu niniejszego dokumentu.
10 |
11 |
12 | [Artykuł Idiomatic CSS w oryginale](https://github.com/necolas/idiomatic-css/)
13 |
14 |
15 | ## Spis treści
16 |
17 | 1. [Główne zasady](#general-principles)
18 | 2. [Wcięcia](#whitespace)
19 | 3. [Komentarze](#comments)
20 | 4. [Format](#format)
21 | 5. [Nazewnictwo](#naming)
22 | 6. [Przykłady praktyczne](#example)
23 | 7. [Organizacja](#organization)
24 | 8. [Przygotowanie i wdrożenie](#build-and-deployment)
25 |
26 | [Podziękowania](#acknowledgements)
27 |
28 |
29 |
30 | ## 1. Główne zasady
31 |
32 | > „Pierwszym krokiem do stworzenia projektu, który odniesie sukces, jest
33 | > zrozumienie, że pisanie kodu dla samego siebie to Bardzo Zły Pomysł®. Jeśli
34 | > z twoich rozwiązań mają korzystać tysiące innych osób, nie pisz tak, jak
35 | > lubisz, ale tak, by osiągnąć maksymalną przejrzystość.” - Idan Gazit
36 |
37 | * Nie jesteś maszyną do kompilowania czy kompresowania kodu i nie staraj się
38 | nią zostać.
39 | * Kod powinien zawsze wyglądać tak, jakby napisał go jeden człowiek -
40 | niezależnie od liczby osób współpracujących przy tym zadaniu.
41 | * Trzymaj się ściśle ustalonych na wstępie reguł.
42 | * Jeśli masz wątpliwości, korzystaj z istniejących, sprawdzonych rozwiązań.
43 |
44 |
45 |
46 | ## 2. Wcięcia
47 |
48 | W całym projekcie stosuj konsekwentnie tylko jeden styl wcięć. Nie zapominaj,
49 | że wcięcia służą przede wszystkim czytelności kodu.
50 |
51 | * _Nigdy_ nie stosuj równolegle spacji i tabulatorów.
52 | * Wybierz jedną z powyższych metod do tworzenia wcięć (najlepiej spacje) i
53 | trzymaj się jej.
54 | * Jeśli używasz spacji, wybierz stałą liczbę znaków dla jednego poziomu wcięcia
55 | (najlepiej cztery).
56 |
57 | Wskazówka: włącz w swoim edytorze kodu opcję pokazywania znaków
58 | niedrukowalnych. To pozwoli ci wyeliminować spacje na końcu linii i w pustych
59 | wierszach.
60 |
61 | Wskazówka: używaj pliku [EditorConfig](http://editorconfig.org/) albo innego
62 | rozwiązania, które pomoże ci trzymać się ustalonych zasad tworzenia wcięć.
63 |
64 |
65 |
66 | ## 3. Komentarze
67 |
68 | Dokładne dokumentowanie kodu jest niezwykle istotne. Poświęć czas na opisanie
69 | komponentów, ich działania i ograniczeń oraz sposobu ich tworzenia. Nie pozwól,
70 | żeby inni członkowie zespołu musieli domyślać się znaczenia kodu.
71 |
72 | Styl tworzenia komentarzy powinien być prosty i spójny w obrębie całego
73 | projektu.
74 |
75 | * Umieszczaj komentarze w nowej linii, nad elementem, który opisują.
76 | * Unikaj tworzenia komentarzy na końcu linii.
77 | * Utrzymuj sensowne maksimum długości linii, np. 80 znaków.
78 | * Używaj komentarzy do dzielenia kodu CSS na osobne sekcje.
79 | * Komentuj, używając standardowych zdań i wcięć akapitów.
80 |
81 | Wskazówka: skonfiguruj swój edytor tak, byś mógł stosować skróty klawiszowe do
82 | wstawiania komentarzy w ustalonej wcześniej postaci.
83 |
84 | #### Przykład:
85 |
86 | ```css
87 | /* ==========================================================================
88 | Blok komentarzy sekcji
89 | ========================================================================== */
90 |
91 | /* Blok komentarzy podsekcji
92 | ========================================================================== */
93 |
94 | /**
95 | * Krótki opis z zastosowaniem formatowania w stylu Doxygen
96 | *
97 | * Długi opis - pierwsze zdanie rozpoczyna się tutaj i biegnie jeszcze przez
98 | * chwilę, zajmując cały wiersz, aby wreszcie zakończyć się konkluzją w tym
99 | * miejscu, u dołu akapitu.
100 | *
101 | * Dłuższy opis jest najlepszym miejscem do umieszczenia szczegółowych
102 | * objaśnień i dokumentacji. Może zawierać przykładowy kod HTML, adresy
103 | * internetowe oraz inne przydatne informacje.
104 | *
105 | * @tag To jest znacznik o nazwie 'tag'
106 | *
107 | * @todo To jest opis todo, wskazujący istotne zadanie, które należy wykonać
108 | * później. Zawija się po około 80 znakach a kolejne linie są wcięte za
109 | * pomocą 2 spacji.
110 | */
111 |
112 | /* Podstawowy komentarz */
113 | ```
114 |
115 |
116 |
117 | ## 4. Format
118 |
119 | Wybrany format kodu musi gwarantować, że kod ten będzie łatwy do przeczytania i
120 | skomentowania, co w efekcie zminimalizuje szanse przypadkowego popełnienia
121 | błędu. W ten sposób także tworzenie przejrzystych zestawień zmian w plikach i
122 | wskazywanie osób odpowiedzialnych za określone poprawki stanie się znacznie
123 | łatwiejszym zadaniem.
124 |
125 | * W deklaracjach z wieloma selektorami używaj jednego selektora w linii.
126 | * Wstawiaj jedną spację przed nawiasem otwierającym zestaw reguł.
127 | * W bloku reguł umieszczaj jedną deklarację w wierszu.
128 | * Stosuj jeden poziom wcięcia dla każdej deklaracji.
129 | * Wstawiaj jedną spację po dwukropku w deklaracji.
130 | * Używaj wartości pisanych małymi literami i skrótów, np. `#aaa`.
131 | * Stosuj pojedyncze i podwójne cudzysłowy w sposób spójny. Preferuj jednak
132 | podwójne, jak na przykład `content: ""`.
133 | * Wyodrędbniaj cudzysłowami wartości atrybutów w selektorach, na przykład
134 | `input[type="checkbox"]`.
135 | * _Tam gdzie to możliwe_ unikaj podawania jednostek dla wartości zerowych, na
136 | przykład `margin: 0`.
137 | * W oddzielonych przecinkami właściwościach wstawiaj spację po każdym
138 | przecinku.
139 | * Pamiętaj o średniku na końcu ostatniej deklaracji w bloku.
140 | * Nawias zamykający zestaw reguł umieszczaj w tej samej kolumnie (z tym samym
141 | wcięciem), co otwierający.
142 | * Bloki deklaracji oddzielaj pustą linią.
143 |
144 | ```css
145 | .selektor-1,
146 | .selektor-2,
147 | .selektor-3[type="text"] {
148 | -webkit-box-sizing: border-box;
149 | -moz-box-sizing: border-box;
150 | box-sizing: border-box;
151 | display: block;
152 | font-family: helvetica, arial, sans-serif;
153 | color: #333;
154 | background: #fff;
155 | background: linear-gradient(#fff, rgba(0, 0, 0, 0.8));
156 | }
157 | ```
158 |
159 | #### Kolejność deklaracji
160 |
161 | Deklaracje powinny być uporządkowane zgodnie z jedną, przyjętą na wstępie
162 | regułą. Preferowanym przeze mnie sposobem jest umieszczanie na początku
163 | właściwości określających strukturę elementu - czyli np. jego pozycję i
164 | wymiary.
165 |
166 | ```css
167 | .selektor {
168 | /* Pozycja */
169 | position: absolute;
170 | z-index: 10;
171 | top: 0;
172 | right: 0;
173 | bottom: 0;
174 | left: 0;
175 |
176 | /* Wyświetlanie i wymiary */
177 | display: inline-block;
178 | overflow: hidden;
179 | box-sizing: border-box;
180 | width: 100px;
181 | height: 100px;
182 | padding: 10px;
183 | border: 10px solid #333;
184 | margin: 10px;
185 |
186 | /* Inne */
187 | background: #000;
188 | color: #fff
189 | font-family: sans-serif;
190 | font-size: 16px;
191 | text-align: right;
192 | }
193 | ```
194 |
195 | Stosunkowo popularne jest także porządkowanie deklaracji alfabetycznie. Metoda
196 | ta ma jednak taką wadę, że oddziela od siebie powiązane właściwości. W takim
197 | wypadku np. definicje marginesów, odstępów, wysokości i szerokości elementu
198 | będą rozrzucone po całym bloku.
199 |
200 | #### Wyjątki i drobne odstępstwa
201 |
202 | Duże fragmenty arkusza zawierające pojedyncze deklaracje można formatować nieco
203 | inaczej, ujmując całość w jednym wierszu. W takim wypadku po nawiasie
204 | otwierającym oraz przed zamykającym należy wstawić spację.
205 |
206 | ```css
207 | .selektor-1 { width: 10%; }
208 | .selektor-2 { width: 20%; }
209 | .selektor-3 { width: 30%; }
210 | ```
211 |
212 | Dłuższe, oddzielone przecinkami właściwości, np. zestawy gradientów albo cieni,
213 | można rozbijać na kilka linii, by poprawić czytelność i ułatwić generowanie
214 | przejrzystych zestawień zmian. Poniższy przykład obrazuje jedno z możliwych
215 | rozwiązań:
216 |
217 | ```css
218 | .selektor {
219 | background-image:
220 | linear-gradient(#fff, #ccc),
221 | linear-gradient(#f3c, #4ec);
222 | box-shadow:
223 | 1px 1px 1px #000,
224 | 2px 2px 1px 1px #ccc inset;
225 | }
226 | ```
227 |
228 | ### Preprocesory: dodatkowe uwagi dotyczące formatu
229 |
230 | Różne narzędzia do wstępnego przetwarzania kodu CSS mają zróżnicowane
231 | możliwości i składnię. W związku z tym zasady postępowania należy ustalać
232 | zawsze w odniesieniu do unikalnych właściwości danego preprocesora. Te wskazane
233 | niżej odnoszą się do jednego z nich - Sass.
234 |
235 | * Ogranicz zagnieżdżanie do jednego poziomu. To pozwoli ci uniknąć tworzenia
236 | nazbyt szczegółowych selektorów.
237 | * Unikaj stosowania dużej liczby zagnieżdżonych reguł. 20 wierszy wydaje się
238 | być rozsądną granicą. Podziel kod na mniejsze fragmenty, gdy tylko zauważysz,
239 | że traci na czytelności.
240 | * Pamiętaj o umieszczaniu `@extend` w pierwszych liniach bloku deklaracji.
241 | * Gdy to możliwe, grupuj `@include` na początku bloku deklaracji, zaraz za
242 | `@extend`.
243 | * Nazwy tworzonych przez siebie funkcji poprzedzaj `x-` lub innym prefiksem.
244 | Pomoże ci to odróżnić je w trakcie pracy od domyślnych funkcji CSS i uniknąć
245 | konfliktów z funkcjami zawartymi w innych bibliotekach.
246 |
247 | ```scss
248 | .selektor-1 {
249 | @extend .inna-regula;
250 | @include clearfix();
251 | @include box-sizing(border-box);
252 | width: x-jednostka-siatki(1);
253 | // pozostałe deklaracje
254 | }
255 | ```
256 |
257 |
258 |
259 | ## 5. Nazewnictwo
260 |
261 | Wybór odpowiedniego nazewnictwa jest trudny, ale bardzo istotny. To kluczowy
262 | element w procesie tworzenia łatwej w aktualizacji i elastycznej bazy kodu
263 | CSS.
264 |
265 | * Unikaj _zbyt częstego_ wykorzystywania skróconych nazw klas. Nie komplikuj
266 | kodu ponad potrzebę.
267 | * Używaj jasnych, kojarzących się, dobrze przemyślanych nazw klas.
268 | * Wybierz zrozumiały i spójny wzorzec tworzenia nazw, który będzie zrozumiały
269 | zarówno w trakcie lektury kodu HTML, jak i CSS.
270 | * Selektory dla komponentów strony powinny wykorzystywać nazwy klas - unikaj
271 | używania nazw tagów i identyfikatorów (id).
272 |
273 | ```css
274 | /* Przykład kodu z kiepskimi nazwami klas */
275 |
276 | .m-prz {
277 | overflow: auto;
278 | }
279 |
280 | .tk {
281 | background: #000;
282 | }
283 |
284 | /* Przykład kodu z lepszymi nazwami */
285 |
286 | .mozna-przewijac {
287 | overflow: auto;
288 | }
289 |
290 | .tekst-kolumny {
291 | background: #000;
292 | }
293 | ```
294 |
295 |
296 |
297 | ## 6. Przykłady praktyczne
298 |
299 | Propozycje zastosowania opisanych wcześniej konwencji.
300 |
301 | ```css
302 | /* ==========================================================================
303 | Siatka
304 | ========================================================================== */
305 |
306 | /**
307 | * Przykładowy kod HTML:
308 | *
309 | *
313 | */
314 |
315 | .siatka {
316 | overflow: visible;
317 | height: 100%;
318 | /* Zapobiegaj zawijaniu tekstu w komórkach z inline-block */
319 | white-space: nowrap;
320 | /* Usuń spacje między komórkami */
321 | font-size: 0;
322 | }
323 |
324 | .komorka {
325 | position: relative;
326 | display: inline-block;
327 | overflow: hidden;
328 | box-sizing: border-box;
329 | width: 20%;
330 | height: 100%;
331 | /* Ustaw odstępy między komórkami */
332 | padding: 0 10px;
333 | border: 2px solid #333;
334 | vertical-align: top;
335 | /* Resetuj spacje */
336 | white-space: normal;
337 | /* Resetuj rozmiar czcionki */
338 | font-size: 16px;
339 | }
340 |
341 | /* Stany komórek */
342 |
343 | .komorka.jest-animowana {
344 | background-color: #fffdec;
345 | }
346 |
347 | /* Wymiary komorek
348 | ========================================================================== */
349 |
350 | .komorka-1 { width: 10%; }
351 | .komorka-2 { width: 20%; }
352 | .komorka-3 { width: 30%; }
353 | .komorka-4 { width: 40%; }
354 | .komorka-5 { width: 50%; }
355 |
356 | /* Modyfikacje komorek
357 | ========================================================================== */
358 |
359 | .komorka--szczegoly,
360 | .komorka--istotne {
361 | border-width: 4px;
362 | }
363 | ```
364 |
365 |
366 |
367 | ## 7. Organizacja
368 |
369 | Odpowiednia organizacja jest istotnym elementem tworzenia każdej bazy kodu CSS.
370 | W przypadku dużych baz to wręcz kwestia kluczowa.
371 |
372 | * Pamiętaj o logicznym wyodrębnianiu samodzielnych fragmentów kodu.
373 | * Używaj osobnych plików (łączonych podczas budowania kodu) aby w prosty sposób
374 | dzielić kod na mniejsze komponenty.
375 | * Jeśli używasz preprocesora, powtarzające się definicje kolorów, typografii
376 | itp. przypisuj do zmiennych.
377 |
378 |
379 |
380 | ## 8. Przygotowanie i wdrożenie
381 |
382 | W projektach powinno się zawsze wdrażać pewne ogólne zasady, według których kod
383 | źródłowy może być analizowany, testowany, kompresowany i wersjonowany przed
384 | wdrożeniem. Doskonałym narzędziem służącym do tego celu jest
385 | [grunt](https://github.com/cowboy/grunt) autorstwa Bena Almana.
386 |
387 |
388 |
389 | ## Podziękowania
390 |
391 | Dziękuję wszystkim, którzy współtworzyli
392 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js). Projekt ten był dla
393 | mnie źródłem inspiracji, cytatów i wskazówek.
394 |
--------------------------------------------------------------------------------
/translations/pt-BR/README.md:
--------------------------------------------------------------------------------
1 | # Princípios para escrever CSS de forma consistente e idiomática
2 |
3 | O documento a seguir descreve um sensato guia de estilo para desenvolvimento
4 | CSS. Não pretendo ser prescritivo e não quero impor as minhas preferências de
5 | estilo no código de outras pessoas. Entretanto, estas orientações incentivam
6 | fortemente o uso de existentes, comuns e sensatos padrões.
7 |
8 | Esse é um documento vivo e novas ideias são sempre bem-vindas. Por favor
9 | contribua.
10 |
11 | [Idiomatic CSS em Inglês (Original)](https://github.com/necolas/idiomatic-css)
12 |
13 |
14 | ## Índice
15 |
16 | 1. [Princípios gerais](#general-principles)
17 | 2. [Espaços em branco](#whitespace)
18 | 3. [Comentários](#comments)
19 | 4. [Formatação](#format)
20 | 5. [Nomeando](#naming)
21 | 6. [Exemplo prático](#example)
22 | 7. [Organização](#organization)
23 | 8. [Build e deploy](#build-and-deployment)
24 |
25 | [Agradecimentos](#acknowledgements)
26 |
27 |
28 |
29 | ## 1. Princípios gerais
30 |
31 | > "Parte de ser um bom gestor de um projeto bem sucedido é perceber que
32 | > escrever código para si mesmo é uma Má Ideia™. Se milhares de pessoas estão
33 | > usando o seu código, então escreva-o com máxima clareza, não sob a sua
34 | > preferência pessoal de como ser esperto com a especificação." - Idan Gazit
35 |
36 | * Todo código em qualquer aplicação deve parecer como se tivesse sido escrito
37 | por uma única pessoa, independentemente de quantas pessoas tenham contribuído.
38 | * Faça cumprir rigorosamente o estilo acordado.
39 | * Em caso de dúvida, utilizar padrões existentes e comuns.
40 |
41 |
42 |
43 | ## 2. Espaços em branco
44 |
45 | Apenas um estilo deve existir em todo o projeto. Seja sempre consistente na
46 | utilização de espaços em branco. Use espaços em branco para melhorar a
47 | legibilidade.
48 |
49 | * _Nunca_ misture espaços e tabs para indentação.
50 | * Escolha entre indentação suave (espaços) ou tabulação. Atenha-se à sua
51 | escolha sem falhar. (Preferência: espaços)
52 | * Se usar espaços, escolha o número de caracteres usados por nível de
53 | indentação. (Preferência: 4 espaços)
54 |
55 | Dica: configure seu editor para "mostrar invisíveis". Isso irá permitir que
56 | você elimine espaços em branco da quebra de linha, elimine espaços em branco de
57 | linhas vazias sem indentação e evite commits poluídos.
58 |
59 | Dica: use um [EditorConfig](http://editorconfig.org/) arquivo (ou equivalente) para ajudar a menter a convenção básica de espaços em branco que você aceitou para sua base de código.
60 |
61 |
62 |
63 | ## 3. Comentários
64 |
65 | Código bem comentado é extremamente importante. Tire tempo para descrever
66 | componentes, como eles funcionam, suas limitações, e o modo como são
67 | construídos. Não deixe outros no time adivinharem o propósito de códigos
68 | incomuns ou não óbvios.
69 |
70 | Estilo de comentário deve ser simples e consistente dentro de uma única base de
71 | código.
72 |
73 | * Coloque comentários em uma nova linha acima do seu assunto.
74 | * Evite comentários no fim da linha.
75 | * Mantenha o comprimento da linha a um máximo sensível, por exemplo, 80
76 | colunas.
77 | * Faça o uso liberal de comentários para quebrar o código CSS em seções
78 | distintas.
79 | * Use comentários com iniciais maiúsculas e indentação de texto consistente.
80 |
81 | Dica: configure seu editor para lhe prover com atalhos a geração do padrão de
82 | comentários acordado.
83 |
84 | #### exemplo com CSS:
85 |
86 | ```css
87 | /* ==========================================================================
88 | Bloco de comentário de seção
89 | ========================================================================== */
90 |
91 | /* Bloco de comentário de sub-seção
92 | ========================================================================== */
93 |
94 | /*
95 | * Bloco de comentário de grupo
96 | * Ideal para explicações em múltiplas linhas e documentação.
97 | */
98 |
99 | /**
100 | * Breve descrição usando o estilo de formato de comentário Doxygen
101 | *
102 | * A primeira frase da descrição longa começa aqui e continua
103 | * nesta linha por um tempo finalmente concluindo aqui no final deste parágrafo.
104 | *
105 | * A descrição longa é ideal para explicações mais detalhadas e documentação.
106 | * Ele pode incluir HTML exemplo, URLs, ou qualquer outra informação
107 | * que seja considerada necessária ou útil.
108 | *
109 | * @tag Esta é uma tag chamada 'tag'
110 | *
111 | * @todo Esta é uma declaração de tarefas que descreve uma tarefa atômica para ser
112 | * concluída numa data posterior. Ela envolve depois de 80 caracteres e as linhas a
113 | * seguir são Recuado por dois espaços.
114 | */
115 |
116 | /* Comentário básico */
117 | ```
118 |
119 | #### exemplo com SCSS:
120 |
121 | ```scss
122 | // ==========================================================================
123 | // Bloco de comentário de seção
124 | // ==========================================================================
125 |
126 | // Bloco de comentário de sub-seção
127 | // ==========================================================================
128 |
129 | //
130 | // Bloco de comentário de grupo
131 | // Ideal para explicações em múltiplas linhas e documentação.
132 | //
133 |
134 | // Comentário básico
135 | ```
136 |
137 |
138 |
139 | ## 4. Formatação
140 |
141 | O formato de código escolhido deve garantir que o código seja: fácil de ler;
142 | fácil de comentar claramente; minimize a chance de introduzir erros
143 | acidentalmente; e resulte em úteis visualizações de diferença.
144 |
145 | * Um seletor discreto por linha em um conjunto de regras com multi-seletores.
146 | * Um único espaço antes da abertura das chaves em um conjunto de regras.
147 | * Uma única declaração por linha em um bloco de declarativo.
148 | * Um nível de indentação para cada declaração.
149 | * Um único espaço depois dos dois pontos de uma declaração.
150 | * Use valores minúsculos e abreviações hexadecimais, por exemplo, `#aaa`.
151 | * Use aspas simples ou duplas de forma consistente. Preferência é por aspas duplas,
152 | por exemplo, `conteúdo:" "`.
153 | * Citação valores de atributos em seletores, por exemplo, `input [type="checkbox"]`.
154 | * _Onde for permitido_, evitar especificar unidades para zero valores, por exemplo, `margin: 0`.
155 | * Inclua um espaço após cada vírgula em propriedades separadas por vírgula ou valores de funções.
156 | * Sempre inclua um ponto-e-vírgula no fim da última declaração em um bloco
157 | declarativo.
158 | * Coloque o fechamento das chaves na mesma coluna que o primeiro caracter do
159 | conjunto de regras.
160 | * Separe cada conjunto de regras por uma linha em branco.
161 |
162 | ```css
163 | .selector-1,
164 | .selector-2,
165 | .selector-3 {
166 | -webkit-box-sizing: border-box;
167 | -moz-box-sizing: border-box;
168 | box-sizing: border-box;
169 | display: block;
170 | color: #333;
171 | background: #fff;
172 | }
173 | ```
174 |
175 | #### Ordem de declaração
176 |
177 | Declarações devem ser ordenadas segundo um único princípio. Minha preferência é
178 | por propriedades relacionadas para serem agrupadas e por propriedades
179 | estruturalmente importantes (por exemplo, posicionamento e box-model) para
180 | serem declaradas antes de propriedades tipográficas, fundo ou cor.
181 |
182 | ```css
183 | .selector {
184 | /* Posicionamento */
185 | position: absolute;
186 | z-index: 10;
187 | top: 0;
188 | right: 0;
189 | bottom: 0;
190 | left: 0;
191 |
192 | /* Display & Modelo de Caixa */
193 | display: inline-block;
194 | overflow: hidden;
195 | box-sizing: border-box;
196 | width: 100px;
197 | height: 100px;
198 | padding: 10px;
199 | border: 10px solid #333;
200 | margin: 10px;
201 |
202 | /* Outros */
203 | background: #000;
204 | color: #fff;
205 | font-family: sans-serif;
206 | font-size: 16px;
207 | text-align: right;
208 | }
209 | ```
210 |
211 | Ordenação alfabética também é popular, mas a desvantagem é que ela separa as
212 | propriedades relacionadas. Por exemplo, deslocamentos de posição não são mais
213 | agrupados e propriedades do box-model podem acabar propagando ao longo de um
214 | bloco de declaração.
215 |
216 | #### Exceções e ligeiros desvios
217 |
218 | Grandes blocos de declarações individuais podem atuar de forma diferente,
219 | através da formatação de linha única. Nesse caso, um espaço deve ser
220 | considerado depois da abertura das chaves e antes do fechamento das chaves.
221 |
222 | ```css
223 | .selector-1 { width: 10%; }
224 | .selector-2 { width: 20%; }
225 | .selector-3 { width: 30%; }
226 | ```
227 |
228 | Longos valores de propriedades separados por vírgula - como coleções de
229 | degradês ou sombras - podem ser organizados em várias linhas em um esforço para
230 | melhorar a legibilidade e produz visualizações de diferença mais úteis. Existem
231 | vários formatos que poderiam ser usados; um exemplo é mostrado abaixo.
232 |
233 | ```css
234 | .selector {
235 | background-image:
236 | linear-gradient(#fff, #ccc),
237 | linear-gradient(#f3c, #4ec);
238 | box-shadow:
239 | 1px 1px 1px #000,
240 | 2px 2px 1px 1px #ccc inset;
241 | }
242 | ```
243 |
244 | #### Miscelânea
245 |
246 | * Use valores hexadecimais em letras minúsculas, por exemplo: `#aaa`.
247 | * Use aspas simples ou duplas de forma consistente. Preferência por aspas
248 | duplas, por exemplo: `content: ""`.
249 | * Sempre coloque aspas em valores de atributos nos seletores, por exemplo:
250 | `input[type="checkbox"]`.
251 | * _Onde permitido_, evite especificar unidades para valores-zero, por exemplo:
252 | `margin: 0`.
253 |
254 | ### Pré-processadores: considerações de formatação adicionais
255 |
256 | Diferentes pré-processadores de CSS possuem diferentes características,
257 | funcionalidades e sintaxe. Suas convenções devem ser extendidas para acomodar
258 | as particularidades de qualquer pré-processador em uso. As seguintes diretrizes
259 | são em referência ao Sass.
260 |
261 | * Limite o aninhamento a 1 nível de profundidade. Reavalie qualquer aninhamento
262 | que tenha mais de 2 níveis de profundidade. Isso impede que existam seletores
263 | CSS muito específicos.
264 | * Evite um grande número de regras aninhadas. Quebre-os para quando a
265 | legibilidade começar a ser afetada. Preferência por evitar aninhamentos que
266 | se espalhem por mais de 20 linhas.
267 | * Sempre coloque as declarações `@extend` nas primeiras linhas de um bloco
268 | declarativo.
269 | * Quando possível, agrupe declarações `@include` no topo de blocos
270 | declarativos, depois de qualquer declaração `@extend`.
271 | * Considere funções customizadas para prefixos com `x-` ou qualquer namespace.
272 | Isso ajuda a evitar qualquer potencial confusão na sua função com a função de
273 | CSS nativo ou de colidir com funções de bibliotecas.
274 |
275 | ```scss
276 | .selector-1 {
277 | @extend .other-rule;
278 | @include clearfix();
279 | @include box-sizing(border-box);
280 | width: x-grid-unit(1);
281 | // other declarations
282 | }
283 | ```
284 |
285 |
286 | ## 5. Nomeando
287 |
288 | Você não é um compilador/compressor de código humano, então não tente ser.
289 |
290 | Use nomes claros e previdentes para classes HTML. Escolha um padrão de nomes
291 | compreensível e consistente que faça sentido para arquivos HTML e arquivos
292 | CSS.
293 |
294 | ```css
295 | /* Exemplo de código com nomes ruins */
296 |
297 | .s-scr {
298 | overflow: auto;
299 | }
300 |
301 | .cb {
302 | background: #000;
303 | }
304 |
305 | /* Exemplo de código com bons nomes */
306 |
307 | .is-scrollable {
308 | overflow: auto;
309 | }
310 |
311 | .column-body {
312 | background: #000;
313 | }
314 | ```
315 |
316 |
317 |
318 | ## 6. Exemplo prático
319 |
320 | Um exemplo de várias convenções.
321 |
322 | ```css
323 | /* ==========================================================================
324 | Grid layout
325 | ========================================================================== */
326 |
327 | /*
328 | * Layout da coluna com scroll horizontal.
329 | *
330 | * Isso cria uma única linha de altura completa, não-envolvendo colunas que podem
331 | * ser navegadas na horizontal dentro de seu pai.
332 | *
333 | * Exemplo de HTML:
334 | *
335 | *
339 | */
340 |
341 | /**
342 | * Grid container
343 | * Deve conter apenas filhos de `.cell`
344 | */
345 |
346 | .grid {
347 | overflow: visible;
348 | height: 100%;
349 | /* Prevent inline-block cells wrapping */
350 | white-space: nowrap;
351 | /* Remove inter-cell whitespace */
352 | font-size: 0;
353 | }
354 |
355 | /**
356 | * Grid cells
357 | * Largura não-explícita por padrão. Extenda com classes `.cell-n`.
358 | */
359 |
360 | .cell {
361 | box-sizing: border-box;
362 | position: relative;
363 | overflow: hidden;
364 | width: 20%;
365 | height: 100%;
366 | /* Set the inter-cell spacing */
367 | padding: 0 10px;
368 | border: 2px solid #333;
369 | vertical-align: top;
370 | /* Reset white-space */
371 | white-space: normal;
372 | /* Reset font-size */
373 | font-size: 16px;
374 | }
375 |
376 | /* Cell states */
377 |
378 | .cell.is-animating {
379 | background-color: #fffdec;
380 | }
381 |
382 | /* Cell dimensions
383 | ========================================================================== */
384 |
385 | .cell-1 { width: 10%; }
386 | .cell-2 { width: 20%; }
387 | .cell-3 { width: 30%; }
388 | .cell-4 { width: 40%; }
389 | .cell-5 { width: 50%; }
390 |
391 | /* Cell modifiers
392 | ========================================================================== */
393 |
394 | .cell--detail,
395 | .cell--important {
396 | border-width: 4px;
397 | }
398 | ```
399 |
400 |
401 |
402 | ## 7. Organização
403 |
404 | Organização de código é uma importante parte de qualquer base de código CSS, e
405 | crucial para grandes bases de código.
406 |
407 | * Separar logicamente distintas partes do código.
408 | * Usar arquivos separados (concatenados por um processo de build) para ajudar a
409 | dividir código para componentes distintos.
410 | * Se estiver usando um pré-processador, abstrair partes comuns de código em
411 | variáveis para cor, tipografia, etc.
412 |
413 |
414 |
415 | ## 8. Build e deploy
416 |
417 | Os projetos devem sempre tentar incluir alguns meios genéricos pelos quais sua
418 | fonte possa ser avaliada, testada, comprimida e versionada em preparação para
419 | uso em produção. Para essa tarefa, o [grunt](https://github.com/cowboy/grunt)
420 | por Ben Alman é uma excelente ferramenta.
421 |
422 |
423 |
424 | ## Agradecimentos
425 |
426 | Obrigado a todos que contribuiram para
427 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js). Foi uma fonte de
428 | inspiração, citações e diretrizes.
429 |
--------------------------------------------------------------------------------
/translations/ru-RU/README.md:
--------------------------------------------------------------------------------
1 | # Принципы написания однородного CSS-кода
2 |
3 | Этот документ представляет собой общие рекомендации по стилю написания CSS. Он
4 | не был задуман как набор жёстких правил, и мне бы не хотелось навязывать
5 | собственные предпочтения другим людям. Тем не менее, данное руководство
6 | призывает к использованию общепринятых и устоявшихся подходов к написанию
7 | кода.
8 |
9 | Этот документ не закончен, и новые идеи всегда приветствуются. Пожалуйста,
10 | внесите свой вклад.
11 |
12 | [«Принципы написания однородного CSS» на английском языке
13 | (Original)](https://github.com/necolas/idiomatic-css)
14 |
15 |
16 | ## Содержание
17 |
18 | 1. [Общие принципы](#general-principles)
19 | 2. [Отступы](#whitespace)
20 | 3. [Комментарии](#comments)
21 | 4. [Форматирование](#format)
22 | 5. [Именование](#naming)
23 | 6. [Практический пример](#example)
24 | 7. [Организация кода](#organization)
25 | 8. [Сборка и развёртывание](#build-and-deployment)
26 |
27 | [Благодарности](#acknowledgements)
28 |
29 |
30 |
31 | ## 1. Общие принципы
32 |
33 | > «Вы сослужите проекту хорошую службу, если будете осознавать, что написание
34 | > кода только для себя — Плохая Идея™. Если тысячи людей используют ваш код, то
35 | > пишите его максимально ясным и не делайте что-то только потому, что
36 | > спецификация языка допускает это». — Idan Gazit
37 |
38 | * Весь код в любом проекте должен выглядеть так, будто его создал один человек,
39 | вне зависимости от того, сколько людей на самом деле принимали участие.
40 | * Строго соблюдайте соглашения.
41 | * В сомнительных случаях используйте общепринятый подход.
42 |
43 |
44 |
45 | ## 2. Отступы
46 |
47 | Для всего проекта должен применяться единый стиль отступов. Всегда будьте
48 | последовательны в использовании отступов и применяйте их для повышения
49 | читабельности кода.
50 |
51 | * _Никогда_ не смешивайте пробелы и табуляцию.
52 | * Между табуляцией и мягкими отступами (пробелы вместо табуляции) выберите
53 | что-то одно. Придерживайтесь своего выбора, не делая исключений.
54 | (Предпочтение: пробелы)
55 | * Если вы используете пробелы, определитесь с количеством символов,
56 | соответствующим одному уровню отступа. (Предпочтение: 4 пробела)
57 |
58 | Совет: настройте редактор кода так, чтобы он отображал невидимые символы. Это
59 | позволит избегать случайных пробелов в конце строк или в пустых строках и легче
60 | отслеживать изменения в коде.
61 |
62 |
63 |
64 | ## 3. Комментарии
65 |
66 | Хорошо откомментированный код очень важен. Потратьте время на то, чтобы описать
67 | компоненты, особенности их работы, ограничения и то, как они были созданы. Не
68 | заставляйте других членов команды гадать над назначением неочевидного кода.
69 |
70 | Стиль комментариев должен быть простым и однородным для всего проекта.
71 |
72 | * Помещайте комментарий на строке перед комментируемым фрагментом кода.
73 | * Избегайте добавления комментариев в конец строки.
74 | * Установите обоснованную максимальную длину строки, например, 80 символов.
75 | * Свободно используйте комментарии для оформления разделов внутри CSS-файла.
76 | * Начинайте предложения с заглавной буквы, в конце ставьте точку, а также
77 | используйте однородные отступы.
78 |
79 | Совет: настройте в редакторе кода горячие клавиши для быстрого набора шаблонов
80 | комментирования.
81 |
82 | #### Пример для CSS:
83 |
84 | ```css
85 | /* ==========================================================================
86 | Блок комментариев для раздела
87 | ========================================================================== */
88 |
89 | /* Блок комментариев для подраздела
90 | ========================================================================== */
91 |
92 | /*
93 | * Блок комментариев для группы правил.
94 | * Хорошо подходит для подробных пояснений и документации.
95 | */
96 |
97 | /* Обычный комментарий */
98 | ```
99 |
100 | #### Пример для SCSS:
101 |
102 | ```scss
103 | // ==========================================================================
104 | // Блок комментариев для раздела
105 | // ==========================================================================
106 |
107 | // Блок комментариев для подраздела
108 | // ==========================================================================
109 |
110 | //
111 | // Блок комментариев для группы правил.
112 | // Хорошо подходит для подробных пояснений и документации.
113 | //
114 |
115 | // Обычный комментарий
116 | ```
117 |
118 |
119 |
120 | ## 4. Форматирование
121 |
122 | Выбранный формат записи кода должен гарантировать, что код легко читается; что
123 | его легко комментировать; должен минимизировать шанс случайного внесения
124 | ошибки; и в результате обеспечивать удобство чтения сообщений внутри системы
125 | управления версиями.
126 |
127 | 1. При создании правила для нескольких селекторов помещайте каждый селектор на
128 | отдельной строке.
129 | 2. Перед открывающей скобкой ставьте один пробел.
130 | 3. Внутри блока объявлений помещайте каждое объявление на отдельной строке.
131 | 4. Добавляйте один уровень отступов перед каждым объявлением.
132 | 5. Ставьте пробел после двоеточия внутри объявления.
133 | 6. Всегда ставьте точку с запятой после последнего объявления в блоке.
134 | 7. Ставьте закрывающую скобку на одной вертикальной линии с первым символом в
135 | селекторе.
136 | 8. Разделяйте правила пустой строкой.
137 |
138 | ```css
139 | .selector-1,
140 | .selector-2,
141 | .selector-3 {
142 | -webkit-box-sizing: border-box;
143 | -moz-box-sizing: border-box;
144 | box-sizing: border-box;
145 | display: block;
146 | color: #333;
147 | background: #fff;
148 | }
149 | ```
150 |
151 | #### Порядок объявлений
152 |
153 | Объявления должны быть упорядочены по единому принципу. Я предпочитаю
154 | объединять их по смыслу и помещать структурно важные свойства (например, те,
155 | что отвечают за позиционирование и блочную модель) перед свойствами, связанными
156 | с типографикой, фоном и цветом.
157 |
158 | ```css
159 | .selector {
160 | position: relative;
161 | display: block;
162 | width: 50%;
163 | height: 100px;
164 | padding: 10px;
165 | border: 0;
166 | margin: 10px;
167 | color: #fff
168 | background: #000;
169 | }
170 | ```
171 |
172 | Упорядочение по алфавиту тоже популярно, но его минус в том, что связанные по
173 | смыслу свойства оказываются разделены. К примеру, свойства, связанные с
174 | отступами, могут встречаться как в начале, так и в конце одного и того же
175 | блока определений.
176 |
177 | #### Исключения и небольшие отклонения
178 |
179 | К большим группам правил, состоящих из одного свойства, может применяться
180 | запись в одну строку. В таком случае следует ставить пробел после открывающей и
181 | перед закрывающей скобками.
182 |
183 | ```css
184 | .selector-1 { width: 10%; }
185 | .selector-2 { width: 20%; }
186 | .selector-3 { width: 30%; }
187 | ```
188 |
189 | Длинные значения свойств, разделяемые запятыми — как, например, набор
190 | градиентов или теней — могут быть помещены на отдельной строке каждое, чтобы
191 | повысить читабельность кода и сообщений в системе управления версиями. Формат
192 | записи может слегка различаться, один из вариантов приведён ниже.
193 |
194 | ```css
195 | .selector {
196 | box-shadow:
197 | 1px 1px 1px #000,
198 | 2px 2px 1px 1px #ccc inset;
199 | background-image:
200 | linear-gradient(#fff, #ccc),
201 | linear-gradient(#f3c, #4ec);
202 | }
203 | ```
204 |
205 | #### Прочее
206 |
207 | * Пишите шестнадцатеричные значения в нижнем регистре, например, `#aaa`.
208 | * Последовательно используйте либо одинарные, либо двойные кавычки. Я
209 | предпочитаю двойные, к примеру, `content: ""`.
210 | * Всегда берите в кавычки значения атрибутов внутри селектора, например,
211 | `input[type="checkbox"]`.
212 | * _Везде, где возможно_, опускайте единицы измерения при нулевом значении,
213 | например, `margin: 0`.
214 |
215 | ### Препроцессоры: дополнительные соглашения
216 |
217 | Разные препроцессоры CSS имеют разный набор возможностей и различный
218 | синтаксис. Ваши соглашения должны быть дополнены, чтобы отражать особенности
219 | использования конкретного препроцессора. Следующий набор правил относится
220 | к Sass.
221 |
222 | * Ограничивайте вложенность одним уровнем. Пересмотрите все правила, в которых
223 | больше двух уровней вложенности. Это позволит избегать чрезмерной
224 | специфичности правил.
225 | * Избегайте большого числа вложенных правил. Оформляйте их отдельно,
226 | когда их становится трудно читать. Предпочтительно ограничивать длину
227 | вложенных правил 20 строками.
228 | * Всегда помещайте оператор `@extend` в первой строке блока объявлений.
229 | * По возможности группируйте операторы `@include` в начале блока объявлений,
230 | сразу после `@extend`.
231 | * Подумайте над добавлением префикса вида `x-` перед своими функциями. Это
232 | позволит избежать возможной путаницы между вашими функциями и стандартными
233 | функциями CSS, а также функциями из сторонних библиотек.
234 |
235 | ```scss
236 | .selector-1 {
237 | @extend .other-rule;
238 | @include clearfix();
239 | @include box-sizing(border-box);
240 | width: x-grid-unit(1);
241 | // прочие объявления
242 | }
243 | ```
244 |
245 |
246 |
247 | ## 5. Именование
248 |
249 | Вы не компилятор и не компрессор кода, поэтому ведите себя соответственно.
250 |
251 | Используйте понятные и осмысленные имена для классов в HTML. Выберите ясный и
252 | последовательный шаблон именования, который будет удобен как для HTML, так и
253 | для CSS.
254 |
255 | ```css
256 | /* Пример кода с плохими именами */
257 |
258 | .s-scr {
259 | overflow: auto;
260 | }
261 |
262 | .cb {
263 | background: #000;
264 | }
265 |
266 | /* Пример лучшего подхода к именованию */
267 |
268 | .is-scrollable {
269 | overflow: auto;
270 | }
271 |
272 | .column-body {
273 | background: #000;
274 | }
275 | ```
276 |
277 |
278 |
279 | ## 6. Практический пример
280 |
281 | Пример использования нескольких соглашений.
282 |
283 | ```css
284 | /* ==========================================================================
285 | Макет сетки
286 | ========================================================================== */
287 |
288 | /*
289 | * HTML для примера:
290 | *
291 | *
295 | */
296 |
297 | .grid {
298 | overflow: visible;
299 | height: 100%;
300 | /* Предотвращаем перенос строчных блоков на новую строку */
301 | white-space: nowrap;
302 | /* Убираем пробелы между ячейками сетки */
303 | font-size: 0;
304 | }
305 |
306 | .cell {
307 | box-sizing: border-box;
308 | position: relative;
309 | overflow: hidden;
310 | width: 20%;
311 | height: 100%;
312 | /* Задаём отступы внутри ячеек */
313 | padding: 0 10px;
314 | border: 2px solid #333;
315 | vertical-align: top;
316 | /* Восстанавливаем поведение по умолчанию */
317 | white-space: normal;
318 | /* Восстанавливаем размер шрифта */
319 | font-size: 16px;
320 | }
321 |
322 | /* Состояния ячеек */
323 |
324 | .cell.is-animating {
325 | background-color: #fffdec;
326 | }
327 |
328 | /* Размеры ячеек
329 | ========================================================================== */
330 |
331 | .cell-1 { width: 10%; }
332 | .cell-2 { width: 20%; }
333 | .cell-3 { width: 30%; }
334 | .cell-4 { width: 40%; }
335 | .cell-5 { width: 50%; }
336 |
337 | /* Модификаторы для ячеек
338 | ========================================================================== */
339 |
340 | .cell--detail,
341 | .cell--important {
342 | border-width: 4px;
343 | }
344 | ```
345 |
346 |
347 |
348 | ## 7. Организация кода
349 |
350 | Организация кода — важная часть любого проекта на CSS и ключевой элемент в
351 | большом проекте.
352 |
353 | * Логически отделяйте различные части кода.
354 | * Используйте отдельные файлы (объединяемые на этапе сборки), чтобы разделить
355 | код обособленных компонентов.
356 | * При использовании препроцессора оформляйте часто используемый код в
357 | переменные, например, для типографики, цветов и т.д.
358 |
359 |
360 |
361 | ## 8. Сборка и развёртывание
362 |
363 | В любом проекте по возможности должны использоваться средства для проверки,
364 | тестирования, сжатия и управления версиями кода при подготовке к развёртыванию.
365 | Хороший инструмент для этих задач —
366 | [grunt](https://github.com/cowboy/grunt), написанный Ben Alman.
367 |
368 |
369 |
370 | ## Благодарности
371 |
372 | Спасибо всем, кто внёс вклад в проект
373 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js). Это мой источник
374 | вдохновения, цитат и общих рекомендаций.
375 |
--------------------------------------------------------------------------------
/translations/sr-SR/README.md:
--------------------------------------------------------------------------------
1 | # Principi pisanja konzistentnog, idiomatskog CSS-a
2 |
3 | Sledeći dokument ocrtava razumne stilove za CSS razvoj. Nije namenjen da bude
4 | perskriptivan i ja ne želim da namećem svoje preferencije stilova na kod drugih
5 | ljudi. Međutim, ove smernice snažno ohrabruju korišćenje postojećih,
6 | zajedničkih, razumnih šema.
7 |
8 | Ovo je "živi" dokument i nove ideje su uvek dobrodošle. Molimo Vas da
9 | doprinesete.
10 |
11 | [Idiomatski CSS na Engleskom (Original)](https://github.com/necolas/idiomatic-css)
12 |
13 |
14 | ## Sadržaj
15 |
16 | 1. [Generalni principi](#general-principles)
17 | 2. [Znaci za razmake](#whitespace)
18 | 3. [Komentari](#comments)
19 | 4. [Formatiranje](#format)
20 | 5. [Imenovanje](#naming)
21 | 6. [Praktični primeri](#example)
22 | 7. [Organizovanje](#organization)
23 | 8. [Izrada i razvoj](#build-and-deployment)
24 |
25 | [Priznanja](#acknowledgements)
26 |
27 |
28 |
29 | ## 1. Generalni principi
30 |
31 | > "Deo zaduženja dobrog stjuarda za uspešan projekat je shvatanje da pisanje
32 | > koda za samog sebe je loša ideja™. Ako hiljade ljudi koristi tvoj kod, onda
33 | > piši tvoj kod sa maksimalnom jasnoćom, a ne sa svojim personalnim
34 | > preferencijama o tome kako da se napraviš pametan u okviru specifikacije." -
35 | > Idan Gazit
36 |
37 | * Sav kod u bilo kom projektu bi trebao da izgleda kao da ga je pisala jedna
38 | osoba, bez obzira koliko je ljudi doprinelo razvoju projekta.
39 | * Striktno primenjujte dogovoreni stil.
40 | * Ako ste u sumnji, koristite postojeće, zajedničke šablone.
41 |
42 |
43 |
44 | ## 2. Znaci za razmake
45 |
46 | Samo jedan stil bi trebao da postoji u celom vašem projektu. Uvek budite
47 | konzistentni u upotrebi razmaka. Koristite razmake da poboljšate čitljivost.
48 |
49 | * _Nikada_ nemojte mešati space karakter i tab za indentaciju.
50 | * Izaberite između mekih indentacija(space karakteri) i pravih tabova. Držite se
51 | vašeg izbora bez obzira na sve. (Preferencija: space karakteri)
52 | * Ako koristite space karaktere, izaberite broj karaktera za indentacioni nivo.
53 | (Preferencija: 4 space karaktera)
54 |
55 | Savet: konfigurišite vaš editor da prikazuje "nevidljive karaktere". Ovo će vam
56 | omogućiti da eliminišete prazne karaktere na kraju linije, da eliminišete space
57 | karaktere praznim linijama i da izbegnete "zagađivanje" komitova.
58 |
59 |
60 |
61 | ## 3. Komentari
62 |
63 | Dobro komentarisan kod je ekstremno bitan. Uzmite vremena da opišete komponente,
64 | kako rade, njihove limite, i način na koji su konstruisani. Nemojte ostavljati
65 | drugim članovima tima da nagađaju svrhu neuobičajenih i ne očiglednih delova
66 | koda.
67 |
68 | Stil komentara treba da bude jednostavan i konzistentan u celom projektu.
69 |
70 | * Postavljajte komentare na novu liniju iznad dela koda koji hoćete da
71 | iskomentarišete.
72 | * Izbegavajte komentare na kraju linije koda.
73 | * Držite dužinu linije na razumnom maksimumu, npr 80 kolona.
74 | * Slobodno koristite komentare da "razbijete" CSS kod na diskretne sekcije.
75 | * Koristite komentare dužine jedne rečenice i konzistentno indentovanje teksta.
76 |
77 |
78 | Savet: konfigurišite vaš editor da vam omogući prečice za ispisivanje unapred
79 | dogovorenog šablona za komentare.
80 |
81 | #### CSS primer:
82 |
83 | ```css
84 | /* ==========================================================================
85 | Blok komentar za odeljak
86 | ========================================================================== */
87 |
88 | /* Blok komentar za pododeljak
89 | ========================================================================== */
90 |
91 | /*
92 | * Blok komentar za grupu.
93 | * Idealan za objašnjavanja koja se protežu u više redova i dokumentaciju.
94 | */
95 |
96 | /* Običan komentar */
97 | ```
98 |
99 | #### SCSS primer:
100 |
101 | ```scss
102 | // ==========================================================================
103 | // Blok komentar za odeljak
104 | // ==========================================================================
105 |
106 | // Blok komentar za pododeljak
107 | // ==========================================================================
108 |
109 | //
110 | // Blok komentar za grupu.
111 | // Idealan za objašnjavanja koja se protežu u više redova i dokumentaciju.
112 | //
113 |
114 | // Običan komentar
115 | ```
116 |
117 |
118 |
119 | ## 4. Formatiranje
120 |
121 | Izabrani tip formatiranja koda mora da obezbedi da je kod: lak za čitanje; lak
122 | da se jasno komentariše; minimizuje šanse da se slučajno uvedu greške; i
123 | rezultira korisnim `diff` i `blame` komandama u vašem sistemu za kontrolu
124 | verzija.
125 |
126 | 1. Jedan selektor na jednu liniju kada koristite više selektora u jednom setu
127 | pravila.
128 | 2. Jedan space karakter pre otvarajuće zagrade za set pravila.
129 | 3. Jedna deklaracija na jednu liniju unutar seta pravila.
130 | 4. Jedan nivo indentacije za svaku deklaraciju.
131 | 5. Jedan space karakter nakon dve tačke u deklaraciju.
132 | 6. Uvek stavite tačku-zarez na kraju poslednje deklaracije u deklarativnom
133 | bloku.
134 | 7. Stavite zatvarajuću zagradu seta pravila u istu kolonu gde se nalazi prvi
135 | karakter selektora tog seta pravila.
136 | 8. Razdvojite svaki set pravila praznom linijom.
137 |
138 | ```css
139 | .selektor-1,
140 | .selektor-2,
141 | .selektor-3 {
142 | -webkit-box-sizing: border-box;
143 | -moz-box-sizing: border-box;
144 | box-sizing: border-box;
145 | display: block;
146 | color: #333;
147 | background: #fff;
148 | }
149 | ```
150 |
151 | #### Redosled deklaracija
152 |
153 | Deklaracije bi trebale biti poređane u skladu sa jednim principom. Moje
154 | preferencije su da slična svojstva budu grupisana zajedno i da strukturno bitna
155 | svojstva (npr pozicioniranje i box-model) budu deklarisana pre svojstava
156 | za tipografiju, pozadine i boje.
157 |
158 | ```css
159 | .selektor {
160 | position: relative;
161 | display: block;
162 | width: 50%;
163 | height: 100px;
164 | padding: 10px;
165 | border: 0;
166 | margin: 10px;
167 | color: #fff
168 | background: #000;
169 | }
170 | ```
171 |
172 | Alfabetni redosled je isto popularan, ali mana mu je da razdvaja slična
173 | svojstva. Na primer, svojstva za pomeranja pozicija više nisu grupisana zajedno
174 | i box-model svojstva mogu da završe raširena kroz ceo deklarativni blok.
175 |
176 | #### Izuzeci i mala odstupanja
177 |
178 | Veliki blokovi gde se nalaze deklaracije u samo jednoj liniji mogu koristiti
179 | malo izmenjen format na jednoj liniji. U ovom slučaju space karakter se
180 | postavlja posle otvarajuće i pre zatvarajuće zagrade.
181 |
182 | ```css
183 | .selektor-1 { width: 10%; }
184 | .selektor-2 { width: 20%; }
185 | .selektor-3 { width: 30%; }
186 | ```
187 |
188 | Dugačka svojstva koja su razdvojena zarezom, kao što su na primer kolekcija
189 | gradijenta ili senka, mogu biti raspoređena preko više linija sve sa ciljem
190 | poboljšanja čitljivosti, a takođe da može da proizvede bolji `diff`. Postoje
191 | razni formati koji bi mogli biti korišćeni, jedan primer je prikazan ispod.
192 |
193 | ```css
194 | .selector {
195 | box-shadow:
196 | 1px 1px 1px #000,
197 | 2px 2px 1px 1px #ccc inset;
198 | background-image:
199 | linear-gradient(#fff, #ccc),
200 | linear-gradient(#f3c, #4ec);
201 | }
202 | ```
203 |
204 | #### Razno
205 |
206 | * Koristite heksadecimalne vrednosti sa malim slovim, npr `#aaa`.
207 | * Koristite jedan ili dupli apostrof konzistentno. Preferencija je da se
208 | koriste dupli apostrofi, npr `content: ""`.
209 | * Vrednosti atributa u selektorima uvek stavljajte između apostrofa, npr
210 | `input[type="checkbox"]`.
211 | * _Gde je moguće_ izbegavajte specifiranje jedinica za nula vrednosti, npr
212 | `margin: 0`.
213 |
214 | ### Preprocesori: dodatna razmatranja za formatiranje
215 |
216 | Različiti CSS preprocesori imaju drugačije karakteristike, funkcionalnosti i
217 | sintaksu. Vaše konvencije bi trebale biti proširene da prime specifičnosti
218 | preprocesora u upotrebi. Sledeće smernice su napomene za Sass.
219 |
220 | * Limitirajte ugnežđenja na 1 nivo dubine. Preispitajte sva gneždenja koja su
221 | dublja od 2 nivoa. Ovo sprečava previše specifične CSS selektore.
222 | * Izbegavajte preveliki boj ugneždenih pravila. Razbijte ih na manje delove
223 | kada to počne da utiče na čitljivost. Preferencije su da izbegavate gnežđenja
224 | koja se rasprostiru na više od 20 linija.
225 | * Uvek postavite `@extend` izjave na prvu liniju deklarativnog bloka.
226 | * Gde je moguće, grupišite `@include` izjave na vrhu deklarativnog bloka, nakon
227 | svih `@extend` izjava.
228 | * Razmotrite upotrebu prefiksa kod custom funkcija sa `x-` ili drugim
229 | namespace-om. Ovo pomaže da se izbegne bilo kakav potencijal da se pobrkaju
230 | vaše funkcije sa nativnim CSS funkcijama, ili da dođe do "sukoba" sa
231 | funkcijama iz drugih biblioteka.
232 |
233 | ```scss
234 | .selektor-1 {
235 | @extend .other-rule;
236 | @include clearfix();
237 | @include box-sizing(border-box);
238 | width: x-grid-unit(1);
239 | // druge deklaracije
240 | }
241 | ```
242 |
243 |
244 |
245 | ## 5. Imenovanje
246 |
247 | Ti nisi ljudski kompajler/kompresor za kod, tako da ne pokušavaj da budeš to.
248 |
249 | Koristi jasna i pažljivo izabrana imena za HTML klase. Izaberi razumljive i
250 | konzistentne šeme za imenovanje koje imaju smisla za korišćenje i u HTML
251 | fajlovima i u CSS fajlovima.
252 |
253 | ```css
254 | /* Primer koda sa lošim imenovanjem */
255 |
256 | .s-scr {
257 | overflow: auto;
258 | }
259 |
260 | .cb {
261 | background: #000;
262 | }
263 |
264 | /* Primer koda sa boljim imenovanjem */
265 |
266 | .is-scrollable {
267 | overflow: auto;
268 | }
269 |
270 | .column-body {
271 | background: #000;
272 | }
273 | ```
274 |
275 |
276 |
277 | ## 6. Praktični primeri
278 |
279 | Primeri raznih konvencija.
280 |
281 | ```css
282 | /* ==========================================================================
283 | Grid layout
284 | ========================================================================== */
285 |
286 | /*
287 | * HTML example:
288 | *
289 | *
293 | */
294 |
295 | .grid {
296 | overflow: visible;
297 | height: 100%;
298 | /* Prevent inline-block cells wrapping */
299 | white-space: nowrap;
300 | /* Remove inter-cell whitespace */
301 | font-size: 0;
302 | }
303 |
304 | .cell {
305 | box-sizing: border-box;
306 | position: relative;
307 | overflow: hidden;
308 | width: 20%;
309 | height: 100%;
310 | /* Set the inter-cell spacing */
311 | padding: 0 10px;
312 | border: 2px solid #333;
313 | vertical-align: top;
314 | /* Reset white-space */
315 | white-space: normal;
316 | /* Reset font-size */
317 | font-size: 16px;
318 | }
319 |
320 | /* Cell states */
321 |
322 | cell.is-animating {
323 | background-color: #fffdec;
324 | }
325 |
326 | /* Cell dimensions
327 | ========================================================================== */
328 |
329 | .cell-1 { width: 10%; }
330 | .cell-2 { width: 20%; }
331 | .cell-3 { width: 30%; }
332 | .cell-4 { width: 40%; }
333 | .cell-5 { width: 50%; }
334 |
335 | /* Cell modifiers
336 | ========================================================================== */
337 |
338 | .cell--detail,
339 | .cell--important {
340 | border-width: 4px;
341 | }
342 | ```
343 |
344 |
345 |
346 | ## 7. Organizacija
347 |
348 | Organizacija koda je važan deo za svaku bazu CSS koda i krucijalan za velike
349 | baze koda.
350 |
351 | * Logična separacija posebnih delova koda.
352 | * Koristite odvojene fajlove(spojene u delu izgradnje za produkciju) da vam
353 | pomogne da razbijete kod u više posebnih komponenti.
354 | * Ako koristite preprocesor, abstraktujte uobičajene delove koda u promenljive,
355 | npr boje, tipografiju, itd.
356 |
357 |
358 |
359 | ## 8. Izgradnja i razvoj
360 |
361 | Projekti bi uvek trebalo da uključe neki generički način da se izvorni kod
362 | "lintuje", testira i kompresuje u pripremi za upotrebu u produkciji. Za ovaj
363 | zadatak, [grunt](https://github.com/cowboy/grunt) od strane Ben Alman-a je
364 | odlična alatka.
365 |
366 |
367 | ## Priznanja
368 |
369 | Hvala svima koji su doprineli
370 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js) projektu. Taj projekat
371 | je bio izvor inspiracije, citata i smernica.
372 |
--------------------------------------------------------------------------------
/translations/tr-TR/README.md:
--------------------------------------------------------------------------------
1 | # Tutarlı, İdiomatic CSS yazma prensipleri
2 |
3 | Aşağıdaki döküman CSS geliştirme konusunda makul bir stil rehberini içerir.
4 | Kuralcı olması ve düşünülmedi ve kendi stil seçimlerini diğer kişilerin koduna
5 | empose etmek istemiyorum. Ama bu yönergeler varolan yaygın ve mantıklı
6 | kalıpların kullanımını teşvik etmektedir.
7 |
8 | Bu yaşayan bir dökümandır ve yeni fikirler daima hoş karşılanacak. Lütfen
9 | katkıda bulunun.
10 |
11 | [İngilizce İdiomatik CSS (Orijinal)](https://github.com/necolas/idiomatic-css)
12 |
13 |
14 | ## İçindekiler
15 |
16 | 1. [Genel Prensipler](#general-principles)
17 | 2. [Beyaz Alanlar](#whitespace)
18 | 3. [Açıklamalar](#comments)
19 | 4. [Format](#format)
20 | 5. [İsimlendirme](#naming)
21 | 6. [Uygulanabilir Örnek](#example)
22 | 7. [Organizasyon](#organization)
23 | 8. [Yapı ve Dağıtma](#build-and-deployment)
24 |
25 | [Acknowledgements](#acknowledgements)
26 |
27 |
28 |
29 | ## 1. Genel Prensipler
30 |
31 | > "Başarılı bir projenin iyi bir temsilci olmanın bir bölümü kendin için kod
32 | > yazmanın kötü bir fikir olduğunun farkına varmaktır. Eğer binlerce insan
33 | > senin kodunun kullanıyorlarsa, o zaman kodunu, şartnameler dahilinde nasıl
34 | > akıllılık yapacağın kişisel seçimlere göre değil maksimum açıklık için yaz."
35 | > - Idan Gazit
36 |
37 | * Herhangi bir kod tababındaki tüm kod, kaç kişi katkıda bulunumuş olursa olsun
38 | sanki tek bir kişi tarafından yazılmış gibi görünmelidir.
39 | * Strictly enforce the agreed upon style.
40 | * Karar verilen stili katı bir şekilde uygula.
41 | * Eğer şüphen varsa yaygın olarak kullanılan yönergeleri uygula.
42 |
43 |
44 |
45 | ## 2. Beyaz Alanlar
46 |
47 | Projenin tüm kaynağında sadece tek bir stil hüküm sürmelidir. Beyaz alan
48 | kullanımında her zaman tutarlı ol. Beyaz alanları okunabilirliği artırmak için
49 | kullan.
50 |
51 | * _Asla_ girintiler için boşluk ve tabları karıştırma.
52 | * Yumuşak girintiler (boşluklar) veya gerçek tablar arasında bir seçim yap.
53 | Seçimine sadık kal. (Tercih: boşluklar)
54 | * Eğer boşluk kullanıyorsan girinti bölümü için kullanılan karakter saysını
55 | seç. (Tercih: 4 boşluk)
56 |
57 | İpucu: Editörünü "görünmezleri göster" şeklinde ayarla. Bu, satır sonu
58 | boşluklarının ve kasıtsız boş satırların önüne geçmeni ve "commit"lerin
59 | kirlenmemesini sağlayacaktır.
60 |
61 |
62 |
63 | ## 3. Açıklamalar
64 |
65 | İyi açıklanmış kod son derece önemlidir. Bileşenleri tanımlamak, nasıl
66 | çalıştıklarını, sınırlamalarını ve nasıl yapıldıklarını açıklamakk için zaman
67 | ayır. Takımdaki diğer kişileri yaygın veya açık olmayan kodu tahmin etmek
68 | zorunda bırakma.
69 |
70 | Açıklama stili basit ve tek bir kod tabanı içinde tutarlı olmalıdır.
71 |
72 | * Açıklamaları iligili öznelerinin üzerinde yeni satıra koy.
73 | * Satır sonu açıklamalarından kaçın.
74 | * Satır uzunluğunu makul bir uzunlukta tut. Ör: 80 sütun.
75 | * CSS kodu farklı aralıklarda kısımlara bölmek için açıklamaları özgürce
76 | kullan.
77 | * Cümle yapısında açıklamalar yap ve tutarlı girintileme kullan.
78 |
79 | İpucu: Editörünü karar vediğin açıklama bloklarının çıktısını verecek şekilde
80 | ayarla.
81 |
82 | #### CSS örneği:
83 |
84 | ```css
85 | /* ==========================================================================
86 | Kısım açıklama bloğu
87 | ========================================================================== */
88 |
89 | /* Alt-kısım açıklama bloğu
90 | ========================================================================== */
91 |
92 | /*
93 | * Grup açıklama bloğu
94 | * Birden fazla satır açıklamalar ve dökümantasyon için ideal.
95 | */
96 |
97 | /* Basit açıklama / yorum */
98 | ```
99 |
100 | #### SCSS örneği:
101 |
102 | ```scss
103 | // ==========================================================================
104 | // Kısım açıklama bloğu
105 | // ==========================================================================
106 |
107 | // Alt-kısım açıklama bloğu
108 | // ==========================================================================
109 |
110 | //
111 | // Grup açıklama bloğu
112 | // Birden fazla satır açıklamalar ve dökümantasyon için ideal.
113 | //
114 |
115 | // Basit açıklama / yorum
116 | ```
117 |
118 |
119 |
120 | ## 4. Format (Biçem)
121 |
122 | Seçilen kod formatı (biçemi) kodun; kolay okunabildiğinden, kolay açıklanabilir
123 | (yorumlamanabilir) olduğundan, kazara hataların oluşmasını minimuma
124 | indirdiğinden ve faydalı "diff" ve hatalar ürettiğinden emin olmalıdır.
125 |
126 | 1. Çoklu seçicilerin olduğu kural setlerinde her satırda tek bir seçici.
127 | 2. Kural setinin açış parantezi önünde tek bir boşluk.
128 | 3. Her deklarasyon bloğunda her satırda tek bir deklarasyon.
129 | 4. Her bir deklarasyon için bir girinti seviyesi.
130 | 5. Deklarasyondaki iki noktadan sonra tek bir boşluk.
131 | 6. Her deklarayon bloğundaki son deklarasyondan sonra mutlaka bir noktalı
132 | virgül kullan
133 | 7. Bir kural setinin sonundaki parantezi o kural setindeki ilk karakter ile
134 | aynı sütuna koy.
135 | 8. Her kural setini boş bir satır ile ayır.
136 |
137 | ```css
138 | .selector-1,
139 | .selector-2,
140 | .selector-3 {
141 | -webkit-box-sizing: border-box;
142 | -moz-box-sizing: border-box;
143 | box-sizing: border-box;
144 | display: block;
145 | color: #333;
146 | background: #fff;
147 | }
148 | ```
149 |
150 | #### Deklarasyon sırası
151 |
152 | Deklarasyonlar tek bir prensibe göre sıralandırılmalıdırlar. Benim seçimim
153 | ilişkili özellikleri beraber gruplamak ve yapısal önemi olan özellikleri (ör:
154 | posizyonlama ve box-model) tipografik, arka plan ve renk özelliklerinden önce
155 | yapmak şeklinde.
156 |
157 | ```css
158 | .selector {
159 | position: relative;
160 | display: block;
161 | width: 50%;
162 | height: 100px;
163 | padding: 10px;
164 | border: 0;
165 | margin: 10px;
166 | color: #fff
167 | background: #000;
168 | }
169 | ```
170 |
171 | Alfabetik sıralama da oldukça popüler ama bunun kusuru ise ilişkili özellikleri
172 | birbirinden ayırması. Örneğin posizyon offsetleri artık beraber gruplanmış
173 | değil ce box-model özellikleri deklarasyon bloğu içinde yayılmış olacaklar.
174 |
175 | #### İstisnalar ve ufak sapmalar
176 |
177 | Tek deklarasyonlu büüyük bloklar biraz daha farklı tek-satır bir biçem
178 | kullanabilirler. Bu açılış parantezinden sonra ve kapanış parantezinden önce
179 | bir boşluk olmalıdır.
180 |
181 | ```css
182 | .selector-1 { width: 10%; }
183 | .selector-2 { width: 20%; }
184 | .selector-3 { width: 30%; }
185 | ```
186 |
187 | Virgülle ayrılmış uzun özellik değerleri - gradient ve gölgeler gibi -
188 | okunabilirliği arttırmak ve daha faydalı "diff"ler yaratmak için birden fazla
189 | satıra yayılabilirler. Bunun için kullanılabilecek çeşitli biçemler var. Bir
190 | örnek aşağıda.
191 |
192 | ```css
193 | .selector {
194 | box-shadow:
195 | 1px 1px 1px #000,
196 | 2px 2px 1px 1px #ccc inset;
197 | background-image:
198 | linear-gradient(#fff, #ccc),
199 | linear-gradient(#f3c, #4ec);
200 | }
201 | ```
202 |
203 | #### Diğer
204 |
205 | * Hex değerlerinde küçük harf kullan, ör., `#aaa`.
206 | * Tek veya çift tırnağı tutarlı kullanın. Tercih çift tırnaktan yana, ör.,
207 | `content: ""`.
208 | * Seçicilerdeki özellik değerlerini her zaman tırnak içine alın, ör.,
209 | `input[type="checkbox"]`.
210 | * _Mümkün olduğu durumlarda_, sıfır değerler için ünite kullanmayın, ör.,
211 | `margin: 0`.
212 |
213 | ### Preprocessors (Önderleyiciler) : dikkate alınacak ek formatlar (biçem)
214 |
215 | Farklı CSS önderleyicileri farklı özelliklere, işlevselliğe ve sözdizimine
216 | (syntax) sahipler. Kurallarınız kullanılmakta olan önderleyecinin özellikleri
217 | ile uyum sağlayacak şekilde olmalıdır. Aşağıdaki yönergeler Sass'ı referans
218 | alarak verilmiştir.
219 |
220 | * Gömmeyi (nesting) sadece 1 bölüm olacak şekilde sınırla. İki seviyeden fazla
221 | olan bütün gömmeleri gözden geçir. Bu aşırı spesifik CSS seçicilerini
222 | engeller.
223 | * Yüksek sayıdaki gömme kurallarını engellemeye çalış. Okunabilirlik
224 | etkilenmeye başladıkça bunları küçük parçalara böl. Tercih 20 satırı aşan
225 | gömmelerin önüne geçmek.
226 | * `@extend` ifadelerini deklarasyon bloğunun ilk satırına koy.
227 | * Mümkün oldukça `@include` ifadelerini deklarasyon bloğunun tepesine `@extend`
228 | ifadelerinden sonrasına koy.
229 | * özel fonksiyonları `x-` veya başka bir isim alanı ile başlat. Bu özel
230 | fonsiyonların CSS fonksiyonları ile karşımasına veya başka kütüphaneler ile
231 | çakışmasına engel olur.
232 |
233 | ```scss
234 | .selector-1 {
235 | @extend .other-rule;
236 | @include clearfix();
237 | @include box-sizing(border-box);
238 | width: x-grid-unit(1);
239 | // other declarations
240 | }
241 | ```
242 |
243 |
244 |
245 | ## 5. İsimlendirme
246 |
247 | Sen bir insan kod derleyicisi/sıkıştırıcı değilsin, dolayısı ile olmaya da
248 | çalışma.
249 |
250 | HTML sınıfları için açık ve iyi düşünülmüş isimler kullan. He HTML hem de CSS
251 | dosyalarında anlamı olan tutarlı bir isimlendirme şekli seç.
252 |
253 | ```css
254 | /* Kötü isim örnekleri kodu */
255 |
256 | .s-scr {
257 | overflow: auto;
258 | }
259 |
260 | .cb {
261 | background: #000;
262 | }
263 |
264 | /* Daha iyi isimli örneklerin kodu */
265 |
266 | .is-scrollable {
267 | overflow: auto;
268 | }
269 |
270 | .column-body {
271 | background: #000;
272 | }
273 | ```
274 |
275 |
276 |
277 | ## 6. Uygulanabilir örnek
278 |
279 | Çeşitli teammüllerin örnekleri.
280 |
281 | ```css
282 | /* ==========================================================================
283 | Grid layout
284 | ========================================================================== */
285 |
286 | /*
287 | * Örnek HTML:
288 | *
289 | *
293 | */
294 |
295 | .grid {
296 | overflow: visible;
297 | height: 100%;
298 | /* inline-block hücrelerin fazla satıra yayılmasını engelle */
299 | white-space: nowrap;
300 | /* Hücre içindeki beyaz alanları kaldır */
301 | font-size: 0;
302 | }
303 |
304 | .cell {
305 | box-sizing: border-box;
306 | position: relative;
307 | overflow: hidden;
308 | width: 20%;
309 | height: 100%;
310 | /* Hücre arası boşluğu ayarla */
311 | padding: 0 10px;
312 | border: 2px solid #333;
313 | vertical-align: top;
314 | /* Beyaz alanları sıfırla */
315 | white-space: normal;
316 | /* Font büyüklüğünü sıfırla */
317 | font-size: 16px;
318 | }
319 |
320 | /* Hücre durumları */
321 |
322 | .cell.is-animating {
323 | background-color: #fffdec;
324 | }
325 |
326 | /* Hücre boyutları
327 | ========================================================================== */
328 |
329 | .cell-1 { width: 10%; }
330 | .cell-2 { width: 20%; }
331 | .cell-3 { width: 30%; }
332 | .cell-4 { width: 40%; }
333 | .cell-5 { width: 50%; }
334 |
335 | /* Hücre değişiklikleri
336 | ========================================================================== */
337 |
338 | .cell--detail,
339 | .cell--important {
340 | border-width: 4px;
341 | }
342 | ```
343 |
344 |
345 |
346 | ## 7. Organizasyon
347 |
348 | Kod organizsayonu bütün CSS kod tabanları için önemlidir ve büyük kod tabanları
349 | içinse kritik önem taşır.
350 |
351 | * Kodun farklı bölümlerini mantıksal bir şekilde ayır.
352 | * Farklı bileşenleri ayırmak için ayrı dosyalar (inşa sırasında birleştirilen)
353 | kullan.
354 | * Eğer bir önderleyici kullanıyorsan, renk, tipografi gibi genel kodları
355 | değişkenlerle soyutla.
356 |
357 |
358 |
359 | ## 8. Yapı ve Dağıtma (Build and deployment)
360 |
361 | Projeler, kaynağın bir şekilde lint edilebileceği, sıkıştırılabileceği, test
362 | edilebileceği, ve üretim için sürümlendirilebileceği soysal (jenerik) bir
363 | yöntem içermelidir. Bunun için Ben Alman'ın
364 | [grunt](https://github.com/cowboy/grunt)'ı mükemmel bir araç.
365 |
366 |
367 |
368 | ## Teşekkürler
369 |
370 | İlham, alıntı ve kılavuz bir kaynak olan
371 | [idiomatic.js](https://github.com/rwldrn/idiomatic.js)'ye katkıda bulunan
372 | herkese teşekkürler.
373 |
--------------------------------------------------------------------------------
/translations/zh-CN/README.md:
--------------------------------------------------------------------------------
1 | # 编写如一、符合习惯的CSS的原则
2 |
3 | 以下文档将概述一个合理的CSS开发风格指导。本指导文件强烈鼓励开发者使用已经存在了的、常见的、合力的文风。您应该有选择地吸纳一些内容来创造您自己的风格指南。
4 |
5 | 这个文档将持续更新,欢迎提出新的想法。还请多多贡献。
6 |
7 | [Principles of writing consistent, idiomatic CSS(原版)](https://github.com/necolas/idiomatic-css)
8 |
9 |
10 | ## 目录
11 |
12 | 1. [通用原则](#general-principles)
13 | 2. [空格](#whitespace)
14 | 3. [注释](#comments)
15 | 4. [格式](#format)
16 | 5. [命名](#naming)
17 | 6. [实例](#example)
18 | 7. [代码组织](#organization)
19 | 8. [构建及部署](#build-and-deployment)
20 |
21 | [致谢](#acknowledgements)
22 |
23 |
24 |
25 | ## 1. 通用原则
26 |
27 | > “作为成功的项目的一员,很重要的一点是意识到只为自己写代码是很糟糕的行为。如果将有成千上万人使用你的代码,
28 | > 那么你需要编写最具明确性的代码,而不是以自我的喜好来彰显自己的智商。” - Idan Gazit
29 |
30 | * 别想着过早地优化代码。先得保证它们可读又可理解才行。
31 | * 在任何代码库中,无论有多少人参与及贡献,所有代码都应该如同一个人编写的一样。
32 | * 严格执行一致认可的风格。
33 | * 如果有疑议,则使用现有的、通用的模式。
34 |
35 |
36 |
37 | ## 2. 空格
38 |
39 | 在项目的所有代码中,应该只有一个风格。在空格的使用上,必须始终保持一致。使用空格来提高可读性。
40 |
41 | * *永远不要*在缩进时混用空格和制表符(又称TAB符号)。
42 | * 在软缩进(使用空格)和真正的制表符间选择其一,并始终坚持这一选择。(推荐使用空格)
43 | * 如果使用空格进行缩进,选择每个缩进所使用的空格数。(推荐:4个空格)
44 |
45 | 提示:将编辑器配置为“显示不可见内容”。这使你可以清除行尾的空格和不需要缩进的空行里的空格,同时可以避免对注释的污染。
46 |
47 | 提示:确定好一种空格格式后,您可以用一个[EditorConfig](http://editorconfig.org/)文件(或者其他相同的东西)来帮助在代码库之间维持这种基本的空格约定。
48 |
49 |
50 | ## 3. 注释
51 |
52 | 良好的注释是非常重要的。请留出时间来描述组件(component)的工作方式、局限性和构建它们的方法。不要让你的团队其它成员
53 | 来猜测一段不通用或不明显的代码的目的。
54 |
55 | 注释的风格应当简洁,并在代码库中保持统一。
56 |
57 | * 将注释放在主题上方并独占一行。
58 | * 控制每行长度在合理的范围内,比如80个字符。
59 | * 使用注释从字面上将CSS代码分隔为独立的部分。
60 | * 注释的大小写应当与普通句子相同,并且使用一致的文本缩进。
61 |
62 | 提示:通过配置编辑器,可以提供快捷键来输出一致认可的注释模式。
63 |
64 | #### CSS示例:
65 |
66 | ```css
67 | /* ==========================================================================
68 | 区块代码注释
69 | ========================================================================== */
70 |
71 | /* 次级区块代码注释
72 | ========================================================================== */
73 |
74 | /**
75 | * “Doxygen式注释格式”的简短介绍
76 | *
77 | * 较长的说明文本从这里开始,这是这段文字的第一句话,而且这句话还
78 | * 没结束,过了好一会儿,我了个去终于结束了,烦不烦啊。
79 | *
80 | * 当需要进行更细致的解释说明、提供文档文本时,较长的说明文本就很
81 | * 有用了。这种长长的说明文本,可以包括示例HTML啦、链接啦等等其
82 | * 他你认为重要或者有用的东西。
83 | *
84 | * @tag 这是一个叫做“tag”的标签。
85 | *
86 | * TODO: 这个“‘需做’陈述”描述了一个接下来要去做的小工作。这种文本,
87 | * 如果超长了的话,应该在80个半角字符(如英文)或40个全角字符(
88 | * 如中文)后便换行,并(在“ * ”的基础上)再在后面缩进两个空格。
89 | */
90 |
91 | /* 一般的注释 */
92 | ```
93 |
94 |
95 | ## 4. 格式
96 |
97 | 最终选择的代码风格必须保证:易于阅读,易于清晰地注释,最小化无意中引入错误的可能性,可生成有用的diff和blame。
98 |
99 | 1. 在多个选择器的规则集中,每个单独的选择器独占一行。
100 | 2. 在规则集的左大括号前保留一个空格。
101 | 3. 在声明块中,每个声明独占一行。
102 | 4. 每个声明前保留一级缩进。
103 | 5. 每个声明的冒号后保留一个空格。
104 | 6. 对于声明块的最后一个声明,始终保留结束的分号。
105 | 7. 规则集的右大括号保持与该规则集的第一个字符在同一列。
106 | 8. 每个规则集之间保留一个空行。
107 |
108 | ```css
109 | .selector-1,
110 | .selector-2,
111 | .selector-3[type="text"] {
112 | -webkit-box-sizing: border-box;
113 | -moz-box-sizing: border-box;
114 | box-sizing: border-box;
115 | display: block;
116 | font-family: helvetica, arial, sans-serif;
117 | color: #333;
118 | background: #fff;
119 | background: linear-gradient(#fff, rgba(0, 0, 0, 0.8));
120 | }
121 |
122 | .selector-a,
123 | .selector-b {
124 | padding: 10px;
125 | }
126 | ```
127 |
128 | #### 声明顺序
129 |
130 | 样式声明的顺序应当遵守一个单一的原则。我的倾向是将相关的属性组合在一起,并且将对结构来说比较重要的属性(如定位或者盒模型)
131 | 放在前面,先于排版、背景及颜色等属性。
132 |
133 | 小型的开发团体,可能会想要把相关的属性声明(比如说定位和箱模型)摆在一起。
134 |
135 | ```css
136 | .selector {
137 | /* Positioning */
138 | position: absolute;
139 | z-index: 10;
140 | top: 0;
141 | right: 0;
142 | bottom: 0;
143 | left: 0;
144 |
145 | /* Display & Box Model */
146 | display: inline-block;
147 | overflow: hidden;
148 | box-sizing: border-box;
149 | width: 100px;
150 | height: 100px;
151 | padding: 10px;
152 | border: 10px solid #333;
153 | margin: 10px;
154 |
155 | /* Other */
156 | background: #000;
157 | color: #fff;
158 | font-family: sans-serif;
159 | font-size: 16px;
160 | text-align: right;
161 | }
162 | ```
163 |
164 | 大型团队,则可能更喜欢按字母排序,因为这样做起来很方便,而且维护起来很容易。
165 |
166 | #### 例外及细微偏移原则的情况
167 |
168 | 对于大量仅包含单条声明的声明块,可以使用一种略微不同的单行格式。在这种情况下,在左大括号之后及右大括号之前都应该保留一个空格。
169 |
170 | ```css
171 | .selector-1 { width: 10%; }
172 | .selector-2 { width: 20%; }
173 | .selector-3 { width: 30%; }
174 | ```
175 |
176 | 对于以逗号分隔并且非常长的属性值 -- 例如一堆渐变或者阴影的声明 -- 可以放在多行中,这有助于提高可读性,并易于生成有效的diff。这种情况下有多
177 | 种格式可以选择,以下展示了一种格式。
178 |
179 | ```css
180 | .selector {
181 | box-shadow:
182 | 1px 1px 1px #000,
183 | 2px 2px 1px 1px #ccc inset;
184 | background-image:
185 | linear-gradient(#fff, #ccc),
186 | linear-gradient(#f3c, #4ec);
187 | }
188 | ```
189 |
190 | #### 杂项
191 |
192 | * 在十六进制值中,使用小写,如`#aaa`。
193 | * 单引号或双引号的选择保持一致。推荐使用双引号,如`content: ""`。
194 | * 对于选择器中的属性值也加上引号,如`input[type="checkbox"]`。
195 | * *如果可以的话*,不要给0加上单位, 如`margin: 0`。
196 |
197 | ### 预处理:格式方面额外的考虑
198 |
199 | 不同的CSS预处理有着不同的特性、功能以及语法。编码习惯应当根据使用的预处理程序进行扩展,以适应其特有的功能。推荐在使用SCSS时遵守以下指导。
200 |
201 | * 将嵌套深度限制在1级。对于超过2级的嵌套,给予重新评估。这可以避免出现过于详实的CSS选择器。
202 | * 避免大量的嵌套规则。当可读性受到影响时,将之打断。推荐避免出现多于20行的嵌套规则出现。
203 | * 始终将`@extend`语句放在声明块的第一行。
204 | * 如果可以的话,将`@include`语句放在声明块的顶部,紧接着`@extend`语句的位置。
205 | * 考虑在自定义函数的名字前加上`x-`或其它形式的前缀。这有助于避免将自己的函数和CSS的原生函数混淆,或函数命名与库函数冲突。
206 |
207 | ```scss
208 | .selector-1 {
209 | @extend .other-rule;
210 | @include clearfix();
211 | @include box-sizing(border-box);
212 | width: x-grid-unit(1);
213 | // other declarations
214 | }
215 | ```
216 |
217 |
218 |
219 | ## 5. 命名
220 |
221 | 不要试着把自己当作编译器或者预处理器,因此命名的时候尽量采用清晰的、有意义的名字。另外,对于
222 | html文件和css文件中的代码,尽量采用一致的命名规则。
223 |
224 |
225 | ```css
226 | /* 没有意义的命名 */
227 | .s-scr {
228 | overflow: auto;
229 | }
230 | .cb {
231 | background: #000;
232 | }
233 |
234 | /* 比较有意义的命名方式 */
235 | .is-scrollable {
236 | overflow: auto;
237 | }
238 | .column-body {
239 | background: #000;
240 | }
241 | ```
242 |
243 |
244 |
245 | ## 6. 实例
246 |
247 | 下面是含有上述约定的示例代码:
248 |
249 | ```css
250 | /* ==========================================================================
251 | Grid layout
252 | ========================================================================== */
253 |
254 | /**
255 | * Column layout with horizontal scroll.
256 | *
257 | * This creates a single row of full-height, non-wrapping columns that can
258 | * be browsed horizontally within their parent.
259 | *
260 | * Example HTML:
261 | *
262 | *
263 | *
264 | *
265 | *
266 | *
267 | */
268 |
269 | /**
270 | * Grid container
271 | *
272 | * Must only contain `.cell` children.
273 | *
274 | * 1. Remove inter-cell whitespace
275 | * 2. Prevent inline-block cells wrapping
276 | */
277 |
278 | .grid {
279 | height: 100%;
280 | font-size: 0; /* 1 */
281 | white-space: nowrap; /* 2 */
282 | }
283 |
284 | /**
285 | * Grid cells
286 | *
287 | * No explicit width by default. Extend with `.cell-n` classes.
288 | *
289 | * 1. Set the inter-cell spacing
290 | * 2. Reset white-space inherited from `.grid`
291 | * 3. Reset font-size inherited from `.grid`
292 | */
293 |
294 | .cell {
295 | position: relative;
296 | display: inline-block;
297 | overflow: hidden;
298 | box-sizing: border-box;
299 | height: 100%;
300 | padding: 0 10px; /* 1 */
301 | border: 2px solid #333;
302 | vertical-align: top;
303 | white-space: normal; /* 2 */
304 | font-size: 16px; /* 3 */
305 | }
306 |
307 | /* Cell states */
308 |
309 | .cell.is-animating {
310 | background-color: #fffdec;
311 | }
312 |
313 | /* Cell dimensions
314 | ========================================================================== */
315 |
316 | .cell-1 { width: 10%; }
317 | .cell-2 { width: 20%; }
318 | .cell-3 { width: 30%; }
319 | .cell-4 { width: 40%; }
320 | .cell-5 { width: 50%; }
321 |
322 | /* Cell modifiers
323 | ========================================================================== */
324 |
325 | .cell--detail,
326 | .cell--important {
327 | border-width: 4px;
328 | }
329 | ```
330 |
331 |
332 |
333 | ## 7. 代码组织
334 |
335 | 对于css代码库来说,如何组织代码文件是很重要的,尤其对于那些很大的代码库显得更加重要。这里介绍
336 | 几个组织代码的建议:
337 |
338 | * 逻辑上对不同的代码进行分离。
339 | * 不同的组件(component)的css尽量用不同的css文件(可以在build阶段用工具合并到一起)
340 | * 如果用到了预处理器(比如less),把一些公共的样式代码抽象成变量,例如颜色,字体等等。
341 |
342 |
343 |
344 | ## 8. 构建及部署
345 |
346 | 任何一个项目,都应该有一个build的过程,在这个阶段我们可以通过工具对代码进行检测,测试,压缩等等,还
347 | 可以为生产环境准备好带有版本号的代码。在这里我推荐一下[grunt](https://github.com/cowboy/grunt)这个工具,我感觉它很不错。
348 |
349 |
350 |
351 | ## 致谢
352 |
353 | 感谢所有对[idiomatic.js](https://github.com/rwldrn/idiomatic.js)作出贡献的网友。
354 |
355 | ##许可
356 | _Principles of writing consistent, idiomatic CSS_ 是Nicolas Gallagher发布在[Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/)许可证下的作品。该许可证适用于本代码栈中的所有文档,包括翻译文本。
357 |
358 | 本作品基于[github.com/necolas/idiomatic-css](https://github.com/necolas/idiomatic-css)著就。
359 |
--------------------------------------------------------------------------------
/translations/zh-TW/README.md:
--------------------------------------------------------------------------------
1 | # 通順一致的CSS編寫原則
2 |
3 | 以下的文件描述了一個合理的CSS開發風格規範。
4 | 這些守則特別著重於使用現有那些普遍且合理的形式。你可以採用它們來創造你自己的風格規範。
5 |
6 | 這是一份持續更新的文件,而且永遠歡迎新的想法,別吝於貢獻。
7 |
8 |
9 | ## 目錄
10 |
11 | 1. [通用原則](#general-principles)
12 | 2. [空格](#whitespace)
13 | 3. [註解](#comments)
14 | 4. [格式](#format)
15 | 5. [實例](#example)
16 |
17 | [Acknowledgements](#acknowledgements)
18 |
19 | [License](#license)
20 |
21 |
22 |
23 | ## 1. 通用原則
24 |
25 | > 「良好管理成功專案的其中一點是能夠了解到
26 | > 只為自己寫代碼是很糟糕的行為。如果有很多人正在使用你寫的代碼,
27 | > 那麼盡可能保持你的代碼明確可讀,而不是在規格中隨個人喜好取巧。」- Idan Gazit
28 |
29 | * 不要嘗試過早地優化你的代碼。讓它保持易讀且容易理解。
30 | * 不論有多少人參與,專案內任何項目的代碼都應該要看起來像是同一人的手筆。
31 | * 嚴格實行被一致認同的風格。
32 | * 當對風格有疑義時應採行現有而普遍的形式。
33 |
34 |
35 |
36 | ## 2. 空格
37 |
38 | 在全部的項目原始碼中只能有唯一的風格,在使用空白時應永遠保持一致性。
39 | 使用空白來提升可讀性。
40 |
41 |
42 | * _絕對_ 不要在縮排時混用空格和跳格。
43 | * 在偽縮排(空格)或是真正的跳格中擇一。並且堅持你的選擇不要漏失。(建議使用:空格)
44 | * 如果使用空格,指定每個縮進等級使用的字元長度。(建議使用:4個空格)
45 |
46 | 提示: 設定你的編輯器「顯示不可見字元」或是自動移除行尾空白。
47 |
48 | 提示: 使用 [EditorConfig](http://editorconfig.org/) 設定檔 (或是類似的工具) 來協助維護項目中已被接受的基本空白慣例。
49 |
50 |
51 |
52 | ## 3. 註解
53 |
54 | 代碼有良好註解是非常重要的。留些時間去描述元件是如何作用,有哪些侷限,以及是如何組成的。
55 | 別讓團隊裡的其他人去猜測那些不尋常的或是意圖不明顯的代碼。
56 |
57 | 註解的風格在同一專案項目中應該力求簡明一致。
58 |
59 | * 將註解放在解釋的對象上方並獨立成行。
60 | * 保持單行長度在一個合理的最大值,例如:80個字元。
61 | * 使用字面上的註解把 CSS 代碼分隔成不同的部分。
62 | * 使用與一般文句相同的大小寫以及一致的段落縮排。
63 |
64 | 提示: 設定你的編輯器以提供快捷鍵來輸出被一致接受的註解形式。
65 |
66 | 範例:
67 |
68 | ```css
69 | /* ==========================================================================
70 | 註解章節區塊
71 | ========================================================================== */
72 |
73 | /* 註解子章節區塊
74 | ========================================================================== */
75 |
76 | /**
77 | * 使用Doxygen風格註解格式的簡短描述
78 | *
79 | * 這一長段敘述的第一個句子從這裡開始,在這行持續一下子,
80 | * 最後收尾在這段的結尾。
81 | *
82 | * 這一長段敘述對於更仔細的解釋以及說明是很合適的。它可以包含一些範例 HTML、URL,
83 | * 或是任何其他有用或必要的資訊。
84 | *
85 | * @tag 這是一個命名為'tag'的標籤
86 | *
87 | * TODO: 這是描述一個要在稍後完成的簡單任務的待辦事項。
88 | * 它在80個字元長度後斷行(譯註:翻成中文後在這裡並非如此)且以下每行
89 | * 都使用兩個空白縮進。
90 | */
91 |
92 | /* 基本註解 */
93 | ```
94 |
95 |
96 |
97 | ## 4. 格式
98 |
99 | 指定的代碼格式必須要確保的是:易於閱讀;易於清晰地註解;減少意外引入錯誤的機會;
100 | 而且可以產生實用的 diff 以及 blame 。
101 |
102 | * 在有許多選擇器的樣式集中,讓每個單獨的選擇器單獨成行。
103 | * 在樣式集的開始括號前保留一個空格。
104 | * 在樣式區塊中保持每個樣式至少一行。
105 | * 在每個樣式前使用一個段落的縮進。
106 | * 在每個樣式的冒號後保留一個空格。
107 | * 使用小寫以及縮略的 HEX 數值,例如:`#aaa`。
108 | * 一致地使用單引號或是雙引號。推薦使用雙引號,例如:`content: ""`。
109 | * 在選擇器中以引號夾注屬性值,例如: `input[type="checkbox"]`。
110 | * _可以的話_,避免在值為零時指定單位,例如:`margin: 0`。
111 | * 在每一個以逗號分隔的屬性的逗號或是函式值後面保留一個空格。
112 | * 在樣式區塊的最後一個樣式結尾保留分號。
113 | * 樣式集的結束括號應該擺放在與樣式集的第一個字元同樣位置。
114 | * 以一個空白行分隔每個樣式集。
115 |
116 | ```css
117 | .selector-1,
118 | .selector-2,
119 | .selector-3[type="text"] {
120 | -webkit-box-sizing: border-box;
121 | -moz-box-sizing: border-box;
122 | box-sizing: border-box;
123 | display: block;
124 | font-family: helvetica, arial, sans-serif;
125 | color: #333;
126 | background: #fff;
127 | background: linear-gradient(#fff, rgba(0, 0, 0, 0.8));
128 | }
129 |
130 | .selector-a,
131 | .selector-b {
132 | padding: 10px;
133 | }
134 | ```
135 |
136 | #### 宣告順序
137 |
138 | 如果宣告按照順序一貫地排列下來,應當要符合一個簡單的原則。
139 |
140 | 比較小的團隊們也許會偏好將有關聯的屬性(例如位置和容器模型)群組在一起。
141 |
142 | ```css
143 | .selector {
144 | /* 位置 */
145 | position: absolute;
146 | z-index: 10;
147 | top: 0;
148 | right: 0;
149 | bottom: 0;
150 | left: 0;
151 |
152 | /* 顯示 & 區塊模型 */
153 | display: inline-block;
154 | overflow: hidden;
155 | box-sizing: border-box;
156 | width: 100px;
157 | height: 100px;
158 | padding: 10px;
159 | border: 10px solid #333;
160 | margin: 10px;
161 |
162 | /* 其它 */
163 | background: #000;
164 | color: #fff;
165 | font-family: sans-serif;
166 | font-size: 16px;
167 | text-align: right;
168 | }
169 | ```
170 |
171 | 比較大的團隊們也許會偏好以字母排序所帶來的簡潔性以及易於維護。
172 |
173 | #### 例外與細微偏差
174 |
175 | 對於大量只包含逐一樣式宣告的區塊,可以採用一種稍微不同的單行格式。
176 | 在這種情況下,應在開始括號之後以及結束括號之前都保留一個空格。
177 |
178 | ```css
179 | .selector-1 { width: 10%; }
180 | .selector-2 { width: 20%; }
181 | .selector-3 { width: 30%; }
182 | ```
183 |
184 | 對於很長且以逗號分隔的屬性值——例如漸層或是陰影的集合——可以整理成多行達到改善可讀性以及產生更有用 diff 的效果,這時有許多種格式可以使用。
185 | 底下有個例子。
186 |
187 | ```css
188 | .selector {
189 | background-image:
190 | linear-gradient(#fff, #ccc),
191 | linear-gradient(#f3c, #4ec);
192 | box-shadow:
193 | 1px 1px 1px #000,
194 | 2px 2px 1px 1px #ccc inset;
195 | }
196 | ```
197 |
198 | ### 預處理器: 額外的格式考量
199 |
200 | 不同的 CSS 預處理器有不同的特色、功能、以及語法。
201 | 應該要考慮到隨著所採用的不同預處理器的特點而去擴充你們的慣例。以下是關於 Sass 的守則。
202 |
203 | * 將嵌套深度限制在一個階層。對於任何兩階以上的深度重新評估。這將避免寫出過於針對性的 CSS 選擇器。
204 | * 避免大量的嵌套規則。當可讀性開始受到影響時將它們打散。盡量避免超過20行的嵌套。
205 | * 永遠將 `@extend` 宣告擺在樣式區塊的第一行。
206 | * 可能的話,將 `@include` 宣告群組置於樣式區塊的頂部,緊接著任何 `@extend` 宣告之後。
207 | * 考慮在自訂函式的前面加上`x-`或是其他的命名空間。這有助於避免與原生的 CSS 函式混淆,或是與其它函式庫衝突。
208 |
209 | ```scss
210 | .selector-1 {
211 | @extend .other-rule;
212 | @include clearfix();
213 | @include box-sizing(border-box);
214 | width: x-grid-unit(1);
215 | // other declarations
216 | }
217 | ```
218 |
219 |
220 |
221 | ## 5. 實例
222 |
223 | 這是遵循上述那些規範的範例。
224 |
225 | ```css
226 | /* ==========================================================================
227 | 格線佈局
228 | ========================================================================== */
229 |
230 | /**
231 | * 帶有橫向捲軸的欄位佈局。
232 | *
233 | * 這會產生一個由全高且不斷開的多欄區塊組成的單列,可以在它的上層容器中橫向瀏覽。
234 | *
235 | * 範例 HTML:
236 | *
237 | *
238 | *
239 | *
240 | *
241 | *
242 | */
243 |
244 | /**
245 | * 格線容器
246 | *
247 | * 必須只包含 `.cell` 子元素.
248 | *
249 | * 1. 移除網格間的空白
250 | * 2. 避免 inline-block 網格斷開
251 | */
252 |
253 | .grid {
254 | height: 100%;
255 | font-size: 0; /* 1 */
256 | white-space: nowrap; /* 2 */
257 | }
258 |
259 | /**
260 | * 系統網格
261 | *
262 | * 不預設固定的寬度. 用 `.cell-n` 類別來變化。
263 | *
264 | * 1. 設定網格內間距
265 | * 2. 重設自 `.grid` 串接來的 white-space 屬性
266 | * 3. 重設自 `.grid` 串接來的 font-size 屬性
267 | */
268 |
269 | .cell {
270 | position: relative;
271 | display: inline-block;
272 | overflow: hidden;
273 | box-sizing: border-box;
274 | height: 100%;
275 | padding: 0 10px; /* 1 */
276 | border: 2px solid #333;
277 | vertical-align: top;
278 | white-space: normal; /* 2 */
279 | font-size: 16px; /* 3 */
280 | }
281 |
282 | /* 網格狀態 */
283 |
284 | .cell.is-animating {
285 | background-color: #fffdec;
286 | }
287 |
288 | /* 網格維度
289 | ========================================================================== */
290 |
291 | .cell-1 { width: 10%; }
292 | .cell-2 { width: 20%; }
293 | .cell-3 { width: 30%; }
294 | .cell-4 { width: 40%; }
295 | .cell-5 { width: 50%; }
296 |
297 | /* 網格修飾
298 | ========================================================================== */
299 |
300 | .cell--detail,
301 | .cell--important {
302 | border-width: 4px;
303 | }
304 | ```
305 |
306 |
307 |
308 | ## Acknowledgements
309 |
310 | Thanks to everyone who has provided translations and to all those who
311 | contributed to [idiomatic.js](https://github.com/rwldrn/idiomatic.js). It was a
312 | source of inspiration, quotations, and guidelines.
313 |
314 |
315 |
316 | ## License
317 |
318 | _Principles of writing consistent, idiomatic CSS_ by Nicolas Gallagher is
319 | licensed under the [Creative Commons Attribution 3.0 Unported
320 | License](http://creativecommons.org/licenses/by/3.0/). This applies to all
321 | documents and translations in this repository.
322 |
323 | Based on a work at
324 | [github.com/necolas/idiomatic-css](https://github.com/necolas/idiomatic-css).
325 |
--------------------------------------------------------------------------------