Sintaxe

  • Revision slug: CSS/sintaxe
  • Revision title: Sintaxe
  • Revision id: 349051
  • Criado:
  • Criador: fvargaspf@gmail.com
  • É a revisão atual? Sim
  • Comentar

Conteúdo da revisão

O Objetivo básico da linguagem de folhas de estilo em cascata (CSS) é permitir que um motor de navegador pinte elementos na página com características específicas como cores, posições, ou decorações. A sintaxe CSS reflete estes objetivos e seus blocos de contrução básicos são:

  • A propriedade é um identificador que possui um nome legível, que define o que será considerado ou editado;
  • O valor descreve como o recurso será tratado pelo motor. Cada propriedade possui um conjunto de valores lálidos, definida por uma gramática formal, bem como um siginificado semântico, implementado para o motor do navegador.

Declarações do CSS

A definição de propriedades CSS para um valor específico é a função principal da linguagem CSS. A propriedade e valor são chamados de declaração, e qualquer motor do CSS calcula quais declarações serão aplicadas para todos um único elemento da página em ordem adequadamente, a fim de exibí-lo com o estilo correto.

Tanto as propriedades como os valores são case-sensitive no CSS. Os pares se separam por dois pontos, ':' (U+003A COLON), e espaços em branco antes, entre e depois de propriedades e valores, porém os espaços dentro da declaração são ignorados.

css syntax - declaration.png

Existem mais de 100 propriedades diferentes no CSS e um número quase infinito de diferentes valores. Nem todos os pares de propriedades e valores são permitidos em cada propriedade define o que são valores válidos. Quando um valor não é válido para uma determinada propriedade, a declaração é considerada inválida e é totalmente ignorada pelo motor do CSS.

Blocos de declaração CSS

Declarações são agrupadas em blocos, que estão delimitados na estrutura com uma chave de abertura, '{' (U+007B LEFT CURLY BRACKET), e fechadas com outra, '}' (U+007D RIGHT CURLY BRACKET). Os blocos as vezes podem estar aninhados, a abertura e fechamento de chaves no bloco CSS deve ser realizada.

css syntax - block.png

Such blocks are naturally called declaration blocks and declarations inside them are separated by a semi-colon, ';' (U+003B SEMICOLON). A declaration block may be empty, that is containing null declaration. White spaces around declarations are ignored. The last declaration of a block doesn't need to be terminated by a semi-colon, though it is often considered good style to do it as it prevents forgetting to add it when extending the block with another declaration.

css syntax - declarations block.png

The content of a CSS declaration block, that is a list of semi-colon-separated declarations, without the initial and closing braces, can be put inside an HTML style attribute.

CSS rulesets

If style sheets could only apply a declaration to each element of a Web page, they would be pretty useless. The real goal is to apply different declarations to different parts of the document.

CSS allows this by associating conditions with declarations blocks. Each (valid) declaration block is preceded by a selector which is a condition selecting some elements of the page. The pair selector-declarations block is called a ruleset, or often simply a rule.

css syntax - ruleset.png

As an element of the page may be matched by several selectors, and therefore by several rules eventually containing a given property several times, with different values, the CSS standard defines which one has precedence over the other and must be applied: this is called the cascade algorithm.

It is important to note that even if a ruleset characterized by a group of selectors is a kind of shorthand replacing rulesets with a single selector each, this doesn't apply to the validity of the ruleset itself.

This leads to an important consequence: if one single basic selector is invalid, like when using an unknown pseudo-element or pseudo-class, the whole selector is invalid and therefor the entire rule is ignored (as invalid too).

CSS statements

Rulesets are the main building blocks of a style sheet, which often consists of only a big list of them. But there is other information that a Web author wants to convey in the style sheet, like the character set, other external style sheets to import, font face or list counter descriptions and many more. It will use other and specific kinds of statements to do that.

A statement is a building block that begins with any non-space characters and ends at the first closing brace or semi-colon (outside a string, non-escaped and not included into another {}, () or [] pair).

css syntax - statements Venn diag.png

There are different kinds of statements:

  • Rulesets (or rules) that, as seen, associate a collection of CSS declarations to a condition described by a selector.
  • At-rules that start with an at sign, '@' (U+0040 COMMERCIAL AT), followed by an identifier and then continuing up the end of the statement, that is up to the next semi-colon (;) outside of a block, or the end of the next block. Each type of at-rules, defined by the identifier, may have its own internal syntax, and semantics of course. They are used to convey meta-data information (like {{ cssxref("@charset") }} or {{ cssxref("@import") }}), conditional information (like {{ cssxref("@media") }} or {{ cssxref("@document") }}), or descriptive information (like {{ cssxref("@font-face") }}).

Any statement which isn't a rule or an at-rule is invalid and ignored.

There is another group of statements, the nested statements, these are statements that can be used in a specific subset of at-rules, the conditional group rules. These statements only apply if a specific condition is matched: the @media at-rule content is applied only if the device on which runs the browser matches the expressed condition; the @document at-rule content is applied only if the current page matches some conditions, and so on. In CSS1 and CSS2.1, only rulesets could be used inside a conditional group rules. That was very restrictive and this restriction was lifted in CSS Conditionals Level 3. Now, though it still is experimental and not support by every browser, a conditional group rules can contain a wider range of content, rulesets but also some, but not all, at-rules.

See also

  • {{ CSS_key_concepts()}}

Fonte da revisão

<p>O Objetivo básico da linguagem de folhas de estilo em cascata (<a href="/en/CSS" title="CSS">CSS</a>) é permitir que um motor de navegador pinte elementos na página com características específicas como cores, posições, ou decorações. A sintaxe <em>CSS </em>reflete estes objetivos e seus blocos de contrução básicos são:</p>
<ul>
  <li>A <strong>propriedade</strong> é um identificador que possui um nome legível, que define o que será considerado ou editado;</li>
  <li>O <strong>valor</strong> descreve como o recurso será tratado pelo motor. Cada propriedade possui um conjunto de valores lálidos, definida por uma gramática formal, bem como um siginificado semântico, implementado para o motor do navegador.</li>
</ul>
<h2 id="Declara.C3.A7.C3.B5es_do_CSS">Declarações do CSS</h2>
<p>A definição de propriedades CSS para um valor específico é a função principal da linguagem CSS. A propriedade e valor são chamados de <strong>declaração</strong>, e qualquer motor do CSS calcula quais declarações serão aplicadas para todos um único elemento da página em ordem <span id="result_box" lang="pt"><span class="hps">adequadamente</span><span>, a fim de</span> exibí-lo<span class="hps">&nbsp;</span><span class="hps">com o estilo</span> correto<span class="hps">.</span></span></p>
<p>Tanto as propriedades como os valores são case-sensitive no CSS. Os pares se separam por dois pontos, '<code>:</code>' (<code>U+003A COLON</code>), e espaços em branco antes, entre e depois de propriedades e valores, porém os espaços dentro da declaração são ignorados.</p>
<p><img alt="css syntax - declaration.png" class="internal default" src="/@api/deki/files/6164/=css_syntax_-_declaration.png" style="border: 1px solid black;padding:1em" /></p>
<p>Existem mais de <a href="https://developer.mozilla.org/en/CSS/CSS_Reference" title="en/CSS/CSS_Reference">100 propriedades diferentes</a> no CSS e um número quase infinito de diferentes valores. Nem todos os pares de propriedades e valores são permitidos em cada propriedade define o que são valores válidos. Quando um valor não é válido para uma determinada propriedade, a declaração é considerada inválida e é totalmente ignorada pelo motor do CSS.</p>
<h2 id="CSS_declarations_blocks">Blocos de declaração CSS</h2>
<p>Declarações são agrupadas em <strong>blocos</strong>, que estão delimitados na estrutura com uma chave de abertura, '<code>{</code>' (<code>U+007B LEFT CURLY BRACKET</code>), e fechadas com outra, '<code>}</code>' (<code>U+007D RIGHT CURLY BRACKET</code>). Os blocos as vezes podem estar aninhados, a abertura e fechamento de chaves no bloco CSS deve ser realizada.</p>
<p><img alt="css syntax - block.png" class="internal default" src="/@api/deki/files/6165/=css_syntax_-_block.png" style="border: 1px solid black; padding: 1em;" /></p>
<p>Such blocks are naturally called <strong>declaration blocks</strong> and declarations inside them are separated by a semi-colon, '<code>;</code>' (<code>U+003B SEMICOLON</code>). A declaration block may be empty, that is containing null declaration. White spaces around declarations are ignored. The last declaration of a block doesn't need to be terminated by a semi-colon, though it is often considered <em>good style</em> to do it as it prevents forgetting to add it when extending the block with another declaration.</p>
<p><img alt="css syntax - declarations block.png" class="internal default" src="/@api/deki/files/6166/=css_syntax_-_declarations_block.png" style="border: 1px solid black; padding: 1em;" /></p>
<div class="note">
  The content of a CSS declaration block, that is a list of semi-colon-separated declarations, without the initial and closing braces, can be put inside an HTML <a href="/en/HTML/Global_attributes#attr-style" title="https://developer.mozilla.org/en/HTML/Global_attributes#attr-style"><code>style</code></a> attribute.</div>
<h2 id="CSS_rulesets">CSS rulesets</h2>
<p>If style sheets could only apply a declaration to each element of a Web page, they would be pretty useless. The real goal is to apply different declarations to different parts of the document.</p>
<p>CSS allows this by associating conditions with declarations blocks. Each (valid) declaration block is preceded by a <em>selector</em> which is a condition selecting some elements of the page. The pair selector-declarations block is called a <strong>ruleset</strong>, or often simply a <strong>rule</strong>.</p>
<p><img alt="css syntax - ruleset.png" class="internal default" src="/@api/deki/files/6167/=css_syntax_-_ruleset.png" style="border: 1px solid black;padding:1em" /></p>
<p>As an element of the page may be matched by several selectors, and therefore by several rules eventually containing a given property several times, with different values, the CSS standard defines which one has precedence over the other and must be applied: this is called the <a href="/en/CSS/Getting_Started/Cascading_and_inheritance" title="Cascading and inheritance">cascade</a> algorithm.</p>
<div class="note">
  It is important to note that even if a ruleset characterized by a group of selectors is a kind of shorthand replacing rulesets with a single selector each, this doesn't apply to the validity of the ruleset itself.<br />
  <br />
  This leads to an important consequence: if one single basic selector is invalid, like when using an unknown pseudo-element or pseudo-class, the whole <em>selector</em> is invalid and therefor the entire rule is ignored (as invalid too).</div>
<h2 id="CSS_statements">CSS statements</h2>
<p>Rulesets are the main building blocks of a style sheet, which often consists of only a big list of them. But there is other information that a Web author wants to convey in the style sheet, like the character set, other external style sheets to import, font face or list counter descriptions and many more. It will use other and specific kinds of statements to do that.</p>
<p>A <strong>statement</strong> is a building block that begins with any non-space characters and ends at the first closing brace or semi-colon (outside a string, non-escaped and not included into another {}, () or [] pair).</p>
<p><img alt="css syntax - statements Venn diag.png" class="internal default" src="/@api/deki/files/6168/=css_syntax_-_statements_Venn_diag.png" style="padding: 1em;" /></p>
<p>There are different kinds of statements:</p>
<ul>
  <li><strong>Rulesets</strong> (or <em>rules</em>) that, as seen, associate a collection of CSS declarations to a condition described by a selector.</li>
  <li><strong>At-rules</strong> that start with an at sign, '<code>@</code>' (<code>U+0040 COMMERCIAL AT</code>), followed by an identifier and then continuing up the end of the statement, that is up to the next semi-colon (;) outside of a block, or the end of the next block. Each type of <a href="/en/CSS/At-rule" title="At-rule">at-rules</a>, defined by the identifier, may have its own internal syntax, and semantics of course. They are used to convey meta-data information (like {{ cssxref("@charset") }} or {{ cssxref("@import") }}), conditional information (like&nbsp;{{ cssxref("@media") }} or {{ cssxref("@document") }}), or descriptive information (like {{ cssxref("@font-face") }}).</li>
</ul>
<p>Any statement which isn't a rule or an at-rule is invalid and ignored.</p>
<p><a name="nested_statements">There is another group of statements, the <strong>nested statements</strong>, these are statements that can be used in a specific subset of at-rules, the <em>conditional group rules</em>. These statements only apply if a specific condition is matched: the <code>@media</code> at-rule content is applied only if the device on which runs the browser matches the expressed condition; the <code>@document</code> at-rule content is applied only if the current page matches some conditions, and so on. In CSS1 and CSS2.1, only <em>rulesets</em> could be used inside a conditional group rules. That was very restrictive and this restriction was lifted in </a><a href="/en/CSS/CSS3#Conditionals" title="en/CSS/CSS3#Conditionals"><em>CSS Conditionals Level 3</em></a>. Now, though it still is experimental and not support by every browser, a conditional group rules can contain a wider range of content, rulesets but also some, but not all, at-rules.</p>
<h2 id="See_also">See also</h2>
<ul>
  <li>{{ CSS_key_concepts()}}</li>
</ul>
Reverter para esta revisão