From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../selectors/attribute_selectors/index.html | 157 +++++ .../learn/css/building_blocks/selectors/index.html | 234 +++++++ .../pt-br/learn/css/css_layout/flexbox/index.html | 342 ++++++++++ .../learn/css/css_layout/fluxo_normal/index.html | 95 +++ files/pt-br/learn/css/css_layout/index.html | 69 ++ .../css/css_layout/intro_leiaute_css/index.html | 707 +++++++++++++++++++++ .../css_layout/layout_de_varias_colunas/index.html | 414 ++++++++++++ .../learn/css/css_layout/positioning/index.html | 574 +++++++++++++++++ .../css/css_layout/responsive_design/index.html | 324 ++++++++++ .../first_steps/como_css_e_estruturado/index.html | 502 +++++++++++++++ .../learn/css/first_steps/how_css_works/index.html | 161 +++++ files/pt-br/learn/css/first_steps/index.html | 56 ++ .../learn/css/first_steps/iniciando/index.html | 265 ++++++++ .../learn/css/first_steps/o_que_e_css/index.html | 127 ++++ .../using_your_new_knowledge/index.html | 96 +++ .../css/howto/css_perguntas_frequentes/index.html | 245 +++++++ files/pt-br/learn/css/howto/index.html | 92 +++ 17 files changed, 4460 insertions(+) create mode 100644 files/pt-br/learn/css/building_blocks/selectors/attribute_selectors/index.html create mode 100644 files/pt-br/learn/css/building_blocks/selectors/index.html create mode 100644 files/pt-br/learn/css/css_layout/flexbox/index.html create mode 100644 files/pt-br/learn/css/css_layout/fluxo_normal/index.html create mode 100644 files/pt-br/learn/css/css_layout/index.html create mode 100644 files/pt-br/learn/css/css_layout/intro_leiaute_css/index.html create mode 100644 files/pt-br/learn/css/css_layout/layout_de_varias_colunas/index.html create mode 100644 files/pt-br/learn/css/css_layout/positioning/index.html create mode 100644 files/pt-br/learn/css/css_layout/responsive_design/index.html create mode 100644 files/pt-br/learn/css/first_steps/como_css_e_estruturado/index.html create mode 100644 files/pt-br/learn/css/first_steps/how_css_works/index.html create mode 100644 files/pt-br/learn/css/first_steps/index.html create mode 100644 files/pt-br/learn/css/first_steps/iniciando/index.html create mode 100644 files/pt-br/learn/css/first_steps/o_que_e_css/index.html create mode 100644 files/pt-br/learn/css/first_steps/using_your_new_knowledge/index.html create mode 100644 files/pt-br/learn/css/howto/css_perguntas_frequentes/index.html create mode 100644 files/pt-br/learn/css/howto/index.html (limited to 'files/pt-br/learn/css') diff --git a/files/pt-br/learn/css/building_blocks/selectors/attribute_selectors/index.html b/files/pt-br/learn/css/building_blocks/selectors/attribute_selectors/index.html new file mode 100644 index 0000000000..98d26ea002 --- /dev/null +++ b/files/pt-br/learn/css/building_blocks/selectors/attribute_selectors/index.html @@ -0,0 +1,157 @@ +--- +title: Attribute selectors +slug: Learn/CSS/Building_blocks/Selectors/Attribute_selectors +translation_of: Learn/CSS/Building_blocks/Selectors/Attribute_selectors +--- +

{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors", "Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements", "Learn/CSS/Building_blocks")}}

+ +

Como você sabe de seu estudo de HTML, os elementos podem ter atributos que fornecem mais detalhes sobre o elemento que está sendo marcado. Em CSS, você pode usar seletores de atributo para direcionar elementos com determinados atributos. Esta lição mostrará como usar esses seletores que são muito úteis.

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.)
Objective:To learn what attribute selectors are and how to use them.
+ +

Seletores de Presença e Valor

+ +

Esses seletores permitem a seleção de um elemento com base na presença de um atributo sozinho (por exemplo, href) ou em várias correspondências diferentes com o valor do atributo.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SelectorExampleDescription
[attr]a[title]Corresponde a elementos com um atributo attr (cujo nome é o valor entre colchetes).
[attr=value]a[href="https://example.com"]Corresponde a elementos com um atributo attr cujo valor é exatamente value - a string entre aspas.
[attr~=value]p[class~="special"] +

Corresponde a elementos com um atributo attr cujo valor é exatamente value, ou contém valor em sua lista de valores (separados por espaço).

+
[attr|=value]div[lang|="zh"]Corresponde a elementos com um atributo attr cujo valor é exatamente value ou começa com value imediatamente seguido por um hífen.
+ +

No exemplo abaixo você pode ver esses seletores sendo usados.

+ + + + + +

{{EmbedGHLiveSample("css-examples/learn/selectors/attribute.html", '100%', 800)}}

+ +

Seletores de SubString

+ +

Esses seletores permitem uma correspondência mais avançada de substrings dentro do valor do seu atributo. Por exemplo, se você tivesse classes de box-warning e box-error e quisesse combinar tudo que começou com a string "box-", você poderia usar [class^="box-"] para selecionar os dois (ou [class|="box"] como descrito abaixo).

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SelectorExampleDescription
[attr^=value]li[class^="box-"]Corresponde a elementos com um atributo attr (cujo nome é o valor entre colchetes), cujo valor começa com valor.
[attr$=value]li[class$="-box"]Corresponde a elementos com um atributo attr cujo valor termina com valor.
[attr*=value]li[class*="box"]Corresponde a elementos com um atributo attr cujo valor contém o valor em qualquer lugar dentro da string.
+ +

(À parte/lado: pode ser útil notar que ^ e $ há muito são usados como âncoras nas chamadas expressões regulares para significar que começa com e termina com.)

+ +

O próximo exemplo mostra o uso desses seletores:

+ + + +

{{EmbedGHLiveSample("css-examples/learn/selectors/attribute-substring.html", '100%', 800)}}

+ +

Case-sensitivity

+ +

Se você deseja combinar valores de atributo sem distinção entre maiúsculas e minúsculas, você pode usar o valor i antes do colchete de fechamento. Este sinalizador informa ao navegador para corresponder caracteres ASCII sem distinção entre maiúsculas e minúsculas. Sem o sinalizador, os valores serão correspondidos de acordo com a distinção entre maiúsculas e minúsculas do idioma do documento - no caso do HTML, será sensível a maiúsculas e minúsculas.

+ +

No exemplo abaixo, o primeiro seletor corresponderá a um valor que começa com um - ele corresponde apenas ao primeiro item da lista porque os outros dois itens da lista começam com um A maiúsculo. O segundo seletor usa o sinalizador que não diferencia maiúsculas de minúsculas e, portanto, corresponde a todos os itens da lista.

+ +

{{EmbedGHLiveSample("css-examples/learn/selectors/attribute-case.html", '100%', 800)}}

+ +
+

Nota: Há tambem um valor mais novo s, que forçará a correspondência com distinção entre maiúsculas e minúsculas em contextos em que a correspondência normalmente não diferencia maiúsculas de minúsculas; no entanto, isso não é bem suportado em navegadores e não é muito útil em um contexto HTML.

+
+ +

Próximos passos

+ +

Agora que terminamos com os seletores de atributo, você pode continuar no próximo artigo e ler sobre pseudo-class and pseudo-element selectors.

+ +

{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors", "Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements", "Learn/CSS/Building_blocks")}}

+ +

In this module

+ +
    +
  1. Cascade and inheritance
  2. +
  3. CSS selectors + +
  4. +
  5. The box model
  6. +
  7. Backgrounds and borders
  8. +
  9. Handling different text directions
  10. +
  11. Overflowing content
  12. +
  13. Values and units
  14. +
  15. Sizing items in CSS
  16. +
  17. Images, media, and form elements
  18. +
  19. Styling tables
  20. +
  21. Debugging CSS
  22. +
  23. Organizing your CSS
  24. +
diff --git a/files/pt-br/learn/css/building_blocks/selectors/index.html b/files/pt-br/learn/css/building_blocks/selectors/index.html new file mode 100644 index 0000000000..34562ced95 --- /dev/null +++ b/files/pt-br/learn/css/building_blocks/selectors/index.html @@ -0,0 +1,234 @@ +--- +title: CSS selectors +slug: Learn/CSS/Building_blocks/Selectors +tags: + - Attribute + - Beginner + - CSS + - Class + - Learn + - NeedsTranslation + - Pseudo + - Selectors + - TopicStub + - id +translation_of: Learn/CSS/Building_blocks/Selectors +--- +
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Cascade_and_inheritance", "Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors", "Learn/CSS/Building_blocks")}}
+ +

Em {{Glossary("CSS")}}, os seletores são usados ​​para direcionar os elementos {{glossary("HTML")}} em nossas páginas da web que queremos estilizar. Há uma grande variedade de seletores CSS disponíveis, permitindo uma precisão refinada ao selecionar os elementos a serem estilizados. Neste artigo e seus sub-artigos, examinaremos os diferentes tipos em grande detalhe, vendo como eles funcionam.

+ + + + + + + + + + + + +
Pré-requisitos:Conhecimento básico de informática, software básico instalado , conhecimento básico de como trabalhar com arquivos , conceitos básicos de HTML (estude Introdução ao HTML ) e uma ideia de como o CSS funciona (estude os primeiros passos do CSS ).
Objetivo:Para saber como os seletores CSS funcionam em detalhes.
+ +

O que é um seletor?

+ +

Você já conheceu os seletores. Um seletor CSS é a primeira parte de uma regra CSS. É um padrão de elementos e outros termos que informam ao navegador quais elementos HTML devem ser selecionados para que os valores de propriedade CSS dentro da regra sejam aplicados a eles. O elemento ou elementos que são selecionados pelo seletor são referidos como o assunto do seletor .

+ +

Some code with the h1 highlighted.

+ +

Em artigos anteriores, você conheceu alguns seletores diferentes e aprendeu que existem seletores que direcionam o documento de maneiras diferentes - por exemplo, selecionando um elemento como h1, ou uma classe como .special.

+ +

Em CSS, os seletores são definidos na especificação dos seletores CSS; como qualquer outra parte do CSS, eles precisam ter suporte em navegadores para funcionarem. A maioria dos seletores que você encontrará são definidos na especificação de Seletores de nível 3 , que é uma especificação madura, portanto, você encontrará um excelente suporte de navegador para esses seletores.

+ +

Listas de seleção

+ +

Se você tiver mais de um item que usa o mesmo CSS, os seletores individuais podem ser combinados em uma lista de seletores para que a regra seja aplicada a todos os seletores individuais. Por exemplo, se eu tiver o mesmo CSS para um h1e também para uma classe de .special, poderia escrever isso como duas regras separadas.

+ +
h1 {
+  color: blue;
+}
+
+.special {
+  color: blue;
+} 
+ +

Eu também poderia combiná-los em uma lista de seletores, adicionando uma vírgula entre eles.

+ +
h1, .special {
+  color: blue;
+} 
+ +

O espaço em branco é válido antes ou depois da vírgula. Você também pode achar os seletores mais legíveis se cada um estiver em uma nova linha.

+ +
h1,
+.special {
+  color: blue;
+} 
+ +

No exemplo ao vivo abaixo, tente combinar os dois seletores que têm declarações idênticas. A exibição visual deve ser a mesma após combiná-los.

+ +

{{EmbedGHLiveSample("css-examples/learn/selectors/selector-list.html", '100%', 1000)}} 

+ +

Ao agrupar seletores dessa forma, se algum seletor for inválido, a regra inteira será ignorada.

+ +

No exemplo a seguir, a regra do seletor de classe inválida será ignorada, enquanto o h1ainda seria estilizado.

+ +
h1 {
+  color: blue;
+}
+
+..special {
+  color: blue;
+} 
+ +

Quando combinados, no entanto, nem o h1nem a classe terão o estilo, pois a regra inteira é considerada inválida.

+ +
h1, ..special {
+  color: blue;
+} 
+ +

Tipos de seletores

+ +

Existem alguns agrupamentos diferentes de seletores e saber qual tipo de seletor você pode precisar o ajudará a encontrar a ferramenta certa para o trabalho. Nos subartículos deste artigo, examinaremos os diferentes grupos de seletores com mais detalhes.

+ +

Seletores de tipo, classe e ID

+ +

Este grupo inclui seletores que têm como alvo um elemento HTML, como um <h1>.

+ +
h1 { }
+ +

Também inclui seletores que direcionam uma classe:

+ +
.box { }
+ +

ou um ID:

+ +
#unique { }
+ +

Seletores de atributos

+ +

Este grupo de seletores oferece diferentes maneiras de selecionar elementos com base na presença de um determinado atributo em um elemento:

+ +
a[title] { }
+ +

Ou até mesmo faça uma seleção com base na presença de um atributo com um valor específico:

+ +
a[href="https://example.com"] { }
+ +

Pseudo classes e pseudo-elementos

+ +

Este grupo de seletores inclui pseudo classes, que definem o estilo de certos estados de um elemento. :hoverpseudoclasse, por exemplo, seleciona um elemento apenas quando ele está sendo passado pelo ponteiro do mouse:

+ +
a:hover { }
+ +

Também inclui pseudoelementos, que selecionam uma determinada parte de um elemento em vez do próprio elemento. Por exemplo, ::first-linesempre seleciona a primeira linha de texto dentro de um elemento (a <p>no caso abaixo), agindo como se a tivesse <span>sido colocado em volta da primeira linha formatada e então selecionado.

+ +
p::first-line { }
+ +

Combinadores

+ +

O grupo final de seletores combina outros seletores para direcionar os elementos em nossos documentos. O seguinte, por exemplo, seleciona parágrafos que são filhos diretos de <article>elementos usando o combinador filho ( >):

+ +
article > p { }
+ +

Próximos passos

+ +

Você pode dar uma olhada na tabela de referência de seletores abaixo para obter links diretos para os vários tipos de seletores nesta seção Aprender ou no MDN em geral, ou continuar para iniciar sua jornada descobrindo sobre seletores de tipo, classe e ID .

+ +

{{PreviousMenuNext("Learn/CSS/Building_blocks/Cascade_and_inheritance", "Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors", "Learn/CSS/Building_blocks")}}

+ +

Tabela de referência de seletores

+ +

A tabela a seguir fornece uma visão geral dos seletores disponíveis para uso, juntamente com links para as páginas deste guia que mostram como usar cada tipo de seletor. Também incluí um link para a página MDN de cada seletor, onde você pode verificar as informações de suporte do navegador. Você pode usar isso como uma referência para voltar quando precisar consultar os seletores mais tarde no material, ou quando você experimentar CSS em geral.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SelectorExampleLearn CSS tutorial
Type selectorh1 {  }Type selectors
Universal selector* {  }The universal selector
Class selector.box {  }Class selectors
id selector#unique { }ID selectors
Attribute selectora[title] {  }Attribute selectors
Pseudo-class selectorsp:first-child { }Pseudo-classes
Pseudo-element selectorsp::first-line { }Pseudo-elements
Descendant combinatorarticle pDescendant combinator
Child combinatorarticle > pChild combinator
Adjacent sibling combinatorh1 + pAdjacent sibling
General sibling combinatorh1 ~ pGeneral sibling
+ +

In this module

+ +
    +
  1. Cascade and inheritance
  2. +
  3. CSS selectors + +
  4. +
  5. The box model
  6. +
  7. Backgrounds and borders
  8. +
  9. Handling different text directions
  10. +
  11. Overflowing content
  12. +
  13. Values and units
  14. +
  15. Sizing items in CSS
  16. +
  17. Images, media, and form elements
  18. +
  19. Styling tables
  20. +
  21. Debugging CSS
  22. +
  23. Organizing your CSS
  24. +
diff --git a/files/pt-br/learn/css/css_layout/flexbox/index.html b/files/pt-br/learn/css/css_layout/flexbox/index.html new file mode 100644 index 0000000000..f6e68c94d7 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/flexbox/index.html @@ -0,0 +1,342 @@ +--- +title: Flexbox +slug: Learn/CSS/CSS_layout/Flexbox +tags: + - Aprender + - Artigo + - CSS + - Caixas Flexíveis + - Flex + - Guía + - Iniciante + - Layout + - flexbox + - grid css + - laioutes css + - ordenação +translation_of: Learn/CSS/CSS_layout/Flexbox +--- +
+

{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/CSS_layout/Practical_positioning_examples", "Learn/CSS/CSS_layout/Grids", "Learn/CSS/CSS_layout")}}

+
+ +

Uma nova tecnologia, mas com suporte bastante difundido entre navegadores, o Flexbox está se tornando apto para uso geral. Flexbox provê ferramentas para criação rápida de layouts complexos e flexíveis, e características que se mostraram historicamente difíceis com CSS. Este artigo explica todos os seus fundamentos.

+ + + + + + + + + + + + +
Pré-requisitos:HTML básico (estude Introdução a HTML), e uma ideia de como CSS funciona (estude Introdução a CSS.)
Objetivo:Aprender como usar o sistema de Flexbox layout para criar web layouts.
+ +

Por quê Flexbox?

+ +

Por um longo tempo, as únicas ferramentas compatíveis entre browsers disponíveis para criação de layouts CSS eram coisas como floats e posicionamento. Estas são boas e funcionam, mas em alguns casos também são limitadas e frustrantes.

+ +

Os requisitos de layouts a seguir são difíceis ou impossíveis de se conseguir com estas ferramentas, em qualquer tipo conveniente e flexível:

+ + + +

Como você verá nas seções subsequentes, flexbox faz muitas tarefas de layouts de maneira mais fácil. Vamos nos aprofundar!

+ +

Introduzindo um exemplo simples

+ +

Neste artigo nós vamos trabalhar uma série de exercícios para ajudá-lo a entender como o flexbox funciona. Para começar, você deve fazer uma cópia local do arquivo inicial — flexbox0.html do nosso repositório no github — carregue-o em um navegador moderno (como Firefox ou Chrome), e abra o arquivo no seu editor de código. Você pode ver a página aqui também.

+ +

Você verá que temos um elemento {{HTMLElement("header")}} com um cabeçalho no nível superior dentro dele, e um elemento {{HTMLElement("section")}} contendo três {{HTMLElement("article")}}s. Nós vamos usá-los para criar um layout padrão de três colunas.

+ +

+ +

Especificando os elementos a serem definidos como caixas flex

+ +

Para iniciar, vamos definir quais elementos serão flexible boxes. Para isto, temos que definir um valor especial de {{cssxref("display")}} no elemento pai dos elementos que queremos afetar. neste caso são os elementos {{HTMLElement("article")}}, portanto vamos definir o valor no elemento {{HTMLElement("section")}} (que se torna um flex container):

+ +
section {
+  display: flex;
+}
+ +

O resultado disso deve ser algo assim:

+ +

+ +

Então, esta única declaração nos dá tudo que precisamos — incrivel, certo? Nós temos um layout de múltiplas com tamanhos iguais, e todas as colunas tem a mesma altura. Isto porque o valor padrão dado aos flex items (os filhos do flex container) são configurados para resolver problemas comuns, como este. Voltaremos a este assunto depois.

+ +
+

Nota: Você pode definir também ao {{cssxref("display")}} o valor inline-flex se quiser colocar os items em linha como flexible boxes.

+
+ +

Um aparte no modelo flex

+ +

Quando os elementos são definidos como flexibles boxes, eles são dispostos ao longo de dois eixos:

+ +

flex_terms.png

+ + + +

Tenha esta terminologia em mente à medida que passar para as seções subsequentes. Você pode voltar a esta referência se ficar confuso quanto aos termos usados inicialmente.

+ +

Colunas ou linhas?

+ +

Flexbox possui uma propriedade chamada {{cssxref("flex-direction")}} que especifica a direção do eixo principal (em qual direção os filhos da flexbox estarão arranjados) — que por padrão seu valor é row (linha), que faz com que eles fiquem arranjados numa linha na direção que o seu navegador está configurado de acordo com a direção de leitura do seu idioma (da esquerda para a direita, no caso do inglês ou português).

+ +

Experimente adicionar a seguinte declaração na seção de sua regra:

+ +
flex-direction: column;
+ +

Você verá que isso organiza os elementos no laioute de coluna, assim como eles estavam antes de adicionarmos qualquer regra CSS. Antes de você seguir, remova essa declaração do seu exemplo.

+ +
+

Nota: Você também pode arranjar itens flexíveis em direção reversa usando os valores row-reverse e column-reverse. Experimente usar esses valores no seu exemplo também!

+
+ +

Embrulhamento

+ +

Um problema que aparece quando você tem uma quantidade fixa de elementos com a mesma largura e altura no seu esquema é que eventualmente seus elementos filhos flexbox irão sobrepor seu elemento pai (container), quebrando o laioute. Dê uma olhada no nosso exemplo flexbox-wrap0.html, e experimente visualizá-lo online (tenha uma cópia local desse arquivo no seu computador se você quiser continuar acompanhando os exemplos):

+ +

+ +

Aqui vemos que os filhos estão de fato saindo fora do elemento recipiente (container). Uma maneira de consertar isso é adicionando a seguinte declaração na seção de sua regra CSS:

+ +
flex-wrap: wrap;
+ +

Experimente isso agora; você verá que o laioute parece muito melhor agora com essa regra:

+ +

Agora temos várias linhas — tantos elementos filhos flexbox estão encaixados em cada linha quantos fazem sentido, e qualquer sobreposição é movida para a próxima linha. A declaração flex: 200px configurada nos elementos {{htmlelement("article")}} significa que cada um terá pelo menos 200 pixels de largura; discutiremos essa propriedade mais detalhadamente mais tarde. Você também deve notar que os últimos filhos na última linha estão mais largos para que a linha inteira possa ser preenchida.

+ +

Mas ainda tem mais para fazermos com isso. Primeiro, experimente mudar sua propriedade {{cssxref("flex-direction")}} para o valor row-reverse — agora você verá que ainda tem um laioute com várias linhas, mas ele começa no canto oposto da janela do navegador e segue na direção reversa.

+ +

Forma abreviada: flex-flow

+ +

A esta altura vale ressaltar que existe uma abreviação para as regras {{cssxref("flex-direction")}} e {{cssxref("flex-wrap")}}: a {{cssxref("flex-flow")}}. Logo, você pode substituir as seguintes regras

+ +
flex-direction: row;
+flex-wrap: wrap;
+ +

por

+ +
flex-flow: row wrap;
+ +

Dimensionamento flexível de elementos flex

+ +

Vamos agora voltar ao nosso primeiro exemplo, e ver como podemos controlar qual a proporção de espaço os elementos flex pode tomar. Localize sua cópia local do arquivo flexbox0.html, ou tenha uma cópia de flexbox1.html como um novo ponto de partida (veja online).

+ +

Primeiro adicione a seguinte regra no final do seu CSS:

+ +
article {
+  flex: 1;
+}
+ +

Esse é um valor relativo sem unidade que define quanto de espaço disponível pelo eixo principal cada elemento flex pode ter. Neste caso, estamos dando para cada elemento {{HTMLElement("article")}} o valor de 1, que significa que eles terão uma quantidade igual de espaço restante depois de coisas como preenchimento ({{cssxref("padding")}}) e margem ({{cssxref("margin")}}) forem definidos. É uma proporção, o que significa que dado que mesmo que você coloque o valor de "400000", para cada elemento flex, terá o mesmo efeito que o valor "1" previamente colocado.

+ +

Agora, adicione a seguinte regra abaixo da última:

+ +
article:nth-of-type(3) {
+  flex: 2;
+}
+ +

Assim que você atualizar a página, você verá que o terceiro elemento {{HTMLElement("article")}} ocupa duas vezes mais do espaço disponível que os outros dois — existe agora quatro unidades na proporção total disponível. Os dois primeiros elementos flex tem uma unidade cada, dessa proporção, logo cada um deles ocupam 1/4 do espaço disponível. O terceiro tem 2 unidades, logo ele ocupa 2/4 (ou metade, 1/2) do espaço disponível. 

+ +

Você também pode especificar um valor de tamanho mínimo para a regra flex. Experimente atualizar a regra para o {{HTMLElement("article")}} existente para que fique assim:

+ +
article {
+  flex: 1 200px;
+}
+
+article:nth-of-type(3) {
+  flex: 2 200px;
+}
+ +

Isso basicamente diz o seguinte: "Para cada elemento flex primeiro será dado 200px do espaço disponível. Depois, o restante do espaço disponível será distribuído entre os elementos, de acordo com a unidade de proporção definida.". Atualize a página e você verá a diferença de como o espaço é distribuído.

+ +

+ +

O valor real de cada caixa flex pode ser visto pela sua flexibilidade/responsividade — se você redimensionar a janela do navegador, ou adicionar outro elemento {{HTMLElement("article")}}, o laioute continua funcionando sem quebrar.

+ +

flex: Forma abreviada ou forma normal?

+ +

{{cssxref("flex")}} é uma propriedade abreviada que pode especificar até três valores diferentes:

+ + + +

Aconselhamos usar sempre a forma abreviada a menos que você precise usar a regra normal (por exemplo para sobrescrever algum valor pré-definido). As regras normais, isto é não abreviadas, geram muito mais código e podem gerar confusão.

+ +

Alinhamento Horizontal e Vertical

+ +

Você também pode usar as funcionalidade do flexbox para alinhar elementos no eixo principal ou no eixo transversal (relembre esse assunto na seção Um aparte no modelo flex). Vamos explorar isso olhando para um outro exemplo — flex-align0.html (veja online) — o qual vamos transformá-lo num botão/barra de ferramentas bem feito e flexível. Neste momento você verá uma barra de menu horizontal, com alguns botões expremidos no canto superior esquerdo:

+ +

+ +

Primeiro, tenha uma cópia local desse exemplo.

+ +

Agora, adicione o seguinte trecho ao final do CSS no arquivo do exemplo:

+ +
div {
+  display: flex;
+  align-items: center;
+  justify-content: space-around;
+}
+ +

Atualize a página e você verá que os botões estão agora bem arranjados no centro, horizontalmente e verticalmente. Fizemos isso através de duas novas propriedades.

+ +
+

Nota: Nesse exemplo, o eixo principal é representado horizontalmente e o eixo transversal é o vertical.

+
+ +

{{cssxref("align-items")}} controla onde os elementos flex ficam no eixo transversal:

+ + + +

Você pode sobrescrever o comportamento de {{cssxref("align-items")}} para elementos individuais, usando a regra {{cssxref("align-self")}} nesses elementos. Por exemplo, experimente adicionar o seguinte trecho no seu CSS:

+ +
button:first-child {
+  align-self: flex-end;
+}
+ +

Veja qual efeito isso dá, e remova novamente quando terminar.

+ +

{{cssxref("justify-content")}} controla onde os elementos flex ficam no eixo principal.

+ + + +

Nós sugerimos que você brinque um pouco mais com essas regras e seus valores para ver como funcionam ainda mais, antes de seguir nos estudos.

+ +

Ordenação de elementos flex

+ +

flexbox também tem uma funcionalidade para alteração da ordem dos elementos flex no laioute, sem afetar a ordem no código fonte HTML. Esta é mais uma coisa que é impossível fazer nos métodos tradicionais de esquema de laioutes.

+ +

O código para fazer isso é bem simples: experimente adicionar o seguinte CSS ao final do código do exemplo da barra de botões:

+ +
button:first-child {
+  order: 1;
+}
+ +

Atualize seu navegador, você verá que o botão "Smile" foi movido para o final do eixo principal. Vamos falar sobre como isso funciona com mais detalhes:

+ + + +

Você também pode usar valores negativos para fazer elementos aparecerem antes do(s) elemento(s) definidos com {{cssxref("order")}} 0 (zero). Por exemplo, Você poderia fazer com que o botão "Blush" aparecesse no começo do eixo principal (horizontal), usando a seguinte regra:

+ +
button:last-child {
+  order: -1;
+}
+ +

Elementos flex aninhados

+ +

É possível criar laioutes bem complexos com flexbox. É perfeitamente aceitável configurar um elemento flex para também ser um container, para que seus filhos também se comportem como caixas flex. Dê uma olhada em complex-flexbox.html (veja também online).

+ +

+ +

O HTML desse exemplo é relativamente simples. Temos um elemento {{HTMLElement("section")}} contendo três {{HTMLElement("article")}}. O terceiro desses {{HTMLElement("article")}} contém três elementos {{HTMLElement("div")}}:

+ +
section - article
+          article
+          article - div - button
+                    div   button
+                    div   button
+                          button
+                          button
+ +

Vamos dar uma olhada no código que usamos no laioute.

+ +

Primeiro, configuramos para que os filhos da {{HTMLElement("section")}} se arranjem como elementos flex.

+ +
section {
+  display: flex;
+}
+ +

Em seguida, configuramos alguns valores flex nos próprios elementos {{HTMLElement("article")}}. Veja especialmente a segunda regra aqui — estamos configurando para que o terceiro {{HTMLElement("article")}} tenha seus filhos arranjados como elementos flex também, mas desta vez eles estarão dispostos em coluna.

+ +
article {
+  flex: 1 200px;
+}
+
+article:nth-of-type(3) {
+  flex: 3 200px;
+  display: flex;
+  flex-flow: column;
+}
+
+ +

Depois, selecionamos o primeiro elemento {{HTMLElement("div")}}. Primeiro usamos flex:1 100px; para efetivamente dar a ele a altura de 100px, depois configuramos para que seus filhos (os elementos {{HTMLElement("button")}}) se arranjem como elementos flex. Aqui, nós os arranjamos em uma linha que os envolvem, e os alinhamos no centro do espaço disponível, como fizemos no exemplo do botão individual que vimos anteriormente:

+ +
article:nth-of-type(3) div:first-child {
+  flex:1 100px;
+  display: flex;
+  flex-flow: row wrap;
+  align-items: center;
+  justify-content: space-around;
+}
+ +

Finalmente, configuramos alguns tamanhos no botão, mas o mais interessante é que demos a ele o valor 1 para a propriedade flex. Isso dá um resultado interessante, que você verá se redimensionar a largura da janela do seu navegador. Esses botões tomarão o máximo de espaço que puderem e ficarão ao máximo na mesma linha, se puderem, mas quando não puderem mais caber na mesma linha, os que estão muito apertados irão para novas linhas de forma que o laioute não quebre e o conteúdo ainda esteja legível ao usuário.

+ +
button {
+  flex: 1;
+  margin: 5px;
+  font-size: 18px;
+  line-height: 1.5;
+}
+ +

Compatibilidade entre navegadores

+ +

O suporte a flexbox está disponível nos navegadores mais novos — Firefox, Chrome, Opera, Microsoft Edge e IE 11, nas versões mais novas do Android e iOS, etc.
+ Contudo você deve estar ciente que ainda existem navegadores antigos em uso que não suportam a regra flexbox (ou até suportam, mas numa versão desatualizada).

+ +

Enquanto você está apenas aprendendo ou testando, a compatibilidade entre navegadores não importa muito; no entanto se você pretende usar o flexbox num site de verdade, você precisa fazer testes e certificar que a experiência do usuário é aceitável em qualquer navegador possível.

+ +

Flexbox é um pouco mais ardiloso que algumas propriedades CSS. Por exemplo, se o suporte a sombras de CSS falta num browser, é muito menos provável de comprometer a usabilidade, afinal apenas as sombras dos elementos que não estarão aparecendo. Contudo, a falta de suporte à propriedade flexbox pode quebrar o laioute do seu site, e comprometer a sua usabilidade.

+ +

Iremos discutir estratégias para contornar problemas complicados de compatibilidade entre navegadores num módulo futuro.

+ +

Sumário

+ +

Isso conclui nosso tour sobre o básico de flexbox. Esperamos que você tenha aproveitado, e que você continue aproveitando enquanto avança com seu aprendizado.
+ No próximo tópico, veremos outro aspecto importante dos Esquemas em CSS: os sistemas de grid, como você pode ver nesse artigo sobre CSS grid layout.

+ +
{{PreviousMenuNext("Learn/CSS/CSS_layout/Practical_positioning_examples", "Learn/CSS/CSS_layout/Grids", "Learn/CSS/CSS_layout")}}
+ +
+

Neste módulo

+ + +
diff --git a/files/pt-br/learn/css/css_layout/fluxo_normal/index.html b/files/pt-br/learn/css/css_layout/fluxo_normal/index.html new file mode 100644 index 0000000000..c27a403fa7 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/fluxo_normal/index.html @@ -0,0 +1,95 @@ +--- +title: Fluxo Normal +slug: Learn/CSS/CSS_layout/Fluxo_Normal +translation_of: Learn/CSS/CSS_layout/Normal_Flow +--- +
{{LearnSidebar}}
+ +

{{PreviousMenuNext("Learn/CSS/CSS_layout/Introduction", "Learn/CSS/CSS_layout/Flexbox", "Learn/CSS/CSS_layout")}}

+ +

Este artigo aborda o Fluxo Normal de alinhamento e acomodação do conteúdo de uma página HTML, na qual o desenvolvedor não inseriu estilos pessoais. Este fluxo é um padrão usado pelos navegodares web. É uma solução preguiçosa ou rápida. Se o Fluxo Normal por ventura não desagradar o programador, poupado será o seu tempo e esforço. Com o ônus adiado para quando ele quiser algo diferente.

+ + + + + + + + + + + + +
Prerrequisitos:Introdução ao HTML (study Introduction to HTML), e uma noção de como o CSS funciona (study Introduction to CSS.)
Objectivo:Explicar qual é o leiaute padrão aplicado pelos navegadores web - a um arquivo HTML - sempre que não houver estilo ou formatos definidos pelo desenvolvedor da referida página.
+ +

Conforme detalhado na última lição de introdução ao leiaute, os elementos em uma página da web acomodam-se em Fluxo Normal, quando não é aplicada qualquer regra CSS para alterar a maneira como estes se comportam.  And, as we began to discover, you can change how elements behave either by adjusting their position in that normal flow, or removing them from it altogether. Starting with a solid, well-structured document that is readable in normal flow is the best way to begin any webpage. It ensures that your content is readable, even if the user is using a very limited browser or a device such as a screen reader that reads out the content of the page. In addition, as normal flow is designed to make a readable document, by starting in this way you are working with the document rather than fighting against it as you make changes to the layout.

+ +

Before digging deeper into different layout methods, it is worth revisiting some of the things you will have studied in previous modules with regard to normal document flow.

+ +

How are elements laid out by default?

+ +

First of all, individual element boxes are laid out by taking the elements' content, then adding any padding, border and margin around them — it's that box model thing again, which we've looked at earlier.

+ +

By default, a block level element's content is 100% of the width of its parent element, and as tall as its content. Inline elements are as tall as their content, and as wide as their content. You can't set width or height on inline elements — they just sit inside the content of block level elements. If you want to control the size of an inline element in this manner, you need to set it to behave like a block level element with display: block; (or even,display: inline-block; which mixes characteristics from both.)

+ +

That explains individual elements, but what about how elements interact with one another? The normal layout flow (mentioned in the layout introduction article) is the system by which elements are placed inside the browser's viewport. By default, block-level elements are laid out in the block flow direction, based on the parent's writing mode (initial: horizontal-tb) — each one will appear on a new line below the last one, and they will be separated by any margin that is set on them. In English therefore, or any other horizontal, top to bottom writing mode, block-level elements are laid out vertically.

+ +

Inline elements behave differently — they don't appear on new lines; instead, they sit on the same line as one another and any adjacent (or wrapped) text content, as long as there is space for them to do so inside the width of the parent block level element. If there isn't space, then the overflowing text or elements will move down to a new line.

+ +

If two adjacent elements both have the margin set on them and the two margins touch, the larger of the two remains, and the smaller one disappears — this is called margin collapsing, and we have met this before too.

+ +

Let's look at a simple example that explains all of this:

+ +
+
<h1>Basic document flow</h1>
+
+<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p>
+
+<p>By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p>
+
+<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p>
+
+<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements will <span>wrap onto a new line if possible (like this one containing text)</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p>
+ +
body {
+  width: 500px;
+  margin: 0 auto;
+}
+
+p {
+  background: rgba(255,84,104,0.3);
+  border: 2px solid rgb(255,84,104);
+  padding: 10px;
+  margin: 10px;
+}
+
+span {
+  background: white;
+  border: 1px solid black;
+}
+
+ +

{{ EmbedLiveSample('Normal_Flow', '100%', 500) }}

+ +

Summary

+ +

Now that you understand normal flow, and how the browser lays things out by default, move on to understand how to change this default display to create the layout needed by your design.

+ +

{{PreviousMenuNext("Learn/CSS/CSS_layout/Introduction", "Learn/CSS/CSS_layout/Flexbox", "Learn/CSS/CSS_layout")}}

+ +

In this module

+ + diff --git a/files/pt-br/learn/css/css_layout/index.html b/files/pt-br/learn/css/css_layout/index.html new file mode 100644 index 0000000000..18740f1b03 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/index.html @@ -0,0 +1,69 @@ +--- +title: CSS layout +slug: Learn/CSS/CSS_layout +tags: + - Beginner + - CSS + - Floating + - Grids + - Guide + - Landing + - Layout + - Learn + - Module + - Multiple column + - NeedsTranslation + - Positioning + - TopicStub + - flexbox + - float +translation_of: Learn/CSS/CSS_layout +--- +
{{LearnSidebar}}
+ +

Até esse ponto nós já vimos fundamentos do CSS, como estilizar textos, e como estilizar e manipular os blocos que envolvem o conteúdo. Chegou a hora de ver como posicionar seus blocos no lugar certo tendo como referência o viewport ou outro elemento. Cobrimos os pré-requisitos necessários para que possamos ir mais a fundo no layout CSS, veremos diferentes configurações de exibição, métodos tradicionais de layout envolvendo float e posicionamento, e ferramentas modernas de layout como flexbox.

+ +

Prerequisitos

+ +

Antes de iniciar esse modulo, você precisa:

+ +
    +
  1. Ter um conhecimento básico de HTML, como discutido no módulo Introdução ao HTML.
  2. +
  3. Estar confortável com os fundamentos do CSS, como discutido em Introdução ao CSS.
  4. +
  5. Entender como estilizar blocos.
  6. +
+ +
+

Nota: Se você estiver trabalhando em um computador/tablete/outro dispositivo em que você não possa criar seus próprios arquivos, você pode testar (muitos dos) os códigos de exemplo em um programa de códigos online como o JSBin ou Thimble.

+
+ +

Guias

+ +

Esse artigo ira introduzir as ferramentas fundamentais para o layout e as técnicas disponiveis no CSS.

+ +
+
Introdução ao CSS
+
Este artigo recapitulará alguns dos recursos de layout CSS que já abordamos em módulos anteriores — como diferentes valores {{cssxref("display")}} — e apresentará alguns dos conceitos que abordaremos ao longo deste módulo.
+
+ +
+
Fluxo normal
+
Os elementos das páginas web apresentam-se de acordo com o fluxo normal (até que façamos algo para mudar isso). Este artigo explica os fundamentos do fluxo normal, bem como uma base para aprender como alterá-lo.
+
Flexbox
+
É um método para criar layout unidimensional, renderizando itens em linhas ou colunas. Os itens flexíveis preenchem os espaços pondendo encolher para caberem em espaços menores. Este artigo explica todos os fundamentos.
+
Grids
+
CSS Grid layout é um sistema de layout bidimensional para páginas web. Ele permite que você coloque conteúdo em linhas e colunas. Tem muitos recursos que facilitam a criação de layouts complexos. Este artigo fornecerá tudo o que você precisa saber para começar a usar Grid layout em suas páginas.
+
+ +
+
Floats
+
Originalmente para imagens flutuantes em blocos de texto, a propriedade {{cssxref("float")}} tornou-se uma das ferramentas mais usadas para criar layouts de várias colunas em páginas web. Com o advento do Flexbox e do Grid o Flot retorna ao seu propósto original. Este artigo explica tudo.
+
Posicionamento
+
O posicionamento permite retirar elementos do fluxo normal do layout do documento fazendo com que se comportem de maneira diferente, por exemplo, posicionando-se um em cima do outro ou permanecendo numa posição fixa no navegador. Este artigo explica os diferentes valores de {{cssxref("position")}} e como usá-los.
+
Layout de múltiplas colunas
+
A especificação de layout de várias colunas fornece um método para colocar conteúdo em colunas, como nos jornais. Este artigo explicará como usar este recurso.
+
Exemplos práticos de posicionamento
+
Com as noções básicas de posicionamento abordadas no último artigo, veremos agora a construção de alguns exemplos do mundo real, para ilustrar que tipos de coisas você pode fazer com o posicionamento.
+
Grids
+
Os sistemas de Grid são outro recurso muito comum usado nos layouts de CSS, que tendem a ser implementados usando flutuadores ou outros recursos de layout. Você imagina seu layout como um número definido de colunas (por exemplo, 4, 6 ou 12) e ajusta suas colunas de conteúdo dentro dessas colunas imaginárias. Neste artigo, exploraremos a idéia básica por trás da criação de um sistema de grade, examinaremos o uso de um sistema de grade pronto fornecido por uma estrutura de grade e terminaremos com a experiência com CSS Grids - um novo recurso de navegador que torna a implementação do design de grade em a Web muito mais fácil.
+
diff --git a/files/pt-br/learn/css/css_layout/intro_leiaute_css/index.html b/files/pt-br/learn/css/css_layout/intro_leiaute_css/index.html new file mode 100644 index 0000000000..9314e8efd3 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/intro_leiaute_css/index.html @@ -0,0 +1,707 @@ +--- +title: Introdução ao leiaute com CSS +slug: Learn/CSS/CSS_layout/Intro_leiaute_CSS +translation_of: Learn/CSS/CSS_layout/Introduction +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/CSS/CSS_layout/Normal_Flow", "Learn/CSS/CSS_layout")}}
+ +

This article will recap some of the CSS layout features we've already touched upon in previous modules — such as different {{cssxref("display")}} values — and introduce some of the concepts we'll be covering throughout this module.

+ + + + + + + + + + + + +
Prerequisites:The basics of HTML (study Introduction to HTML), and an idea of How CSS works (study Introduction to CSS.)
Objective:To give you an overview of CSS page layout techniques. Each technique can be learned in greater detail in subsequent tutorials.
+ +

CSS page layout techniques allow us to take elements contained in a web page and control where they are positioned relative to their default position in normal layout flow, the other elements around them, their parent container, or the main viewport/window.  The page layout techniques we'll be covering in more detail in this module are

+ + + +

Each technique has its uses, advantages, and disadvantages, and no technique is designed to be used in isolation. By understanding what each method is designed for you will be in a good place to understand which is the best layout tool for each task.

+ +

Normal flow

+ +

Normal flow is how the browser lays out HTML pages by default when you do nothing to control page layout. Let's look at a quick HTML example:

+ +
<p>I love my cat.</p>
+
+<ul>
+  <li>Buy cat food</li>
+  <li>Exercise</li>
+  <li>Cheer up friend</li>
+</ul>
+
+<p>The end!</p>
+ +

By default, the browser will display this code as follows:

+ +

{{ EmbedLiveSample('Normal_flow', '100%', 200) }}

+ +

Note here how the HTML is displayed in the exact order in which it appears in the source code, with elements stacked up on top of one another — the first paragraph, followed by the unordered list, followed by the second paragraph.

+ +

The elements that appear one below the other are described as block elements, in contrast to inline elements, which appear one beside the other, like the individual words in a paragraph.

+ +
+

Note: The direction in which block element contents are laid out is described as the Block Direction. The Block Direction runs vertically in a language such as English, which has a horizontal writing mode. It would run horizontally in any language with a Vertical Writing Mode, such as Japanese. The corresponding Inline Direction is the direction in which inline contents (such as a sentence) would run.

+
+ +

When you use CSS to create a layout, you are moving the elements away from the normal flow, but for many of the elements on your page the normal flow will create exactly the layout you need. This is why starting with a well-structured HTML document is so important, as you can then work with the way things are laid out by default rather than fighting against it.

+ +

The methods that can change how elements are laid out in CSS are as follows:

+ + + +

The display property

+ +

The main methods of achieving page layout in CSS are all values of the display property. This property allows us to change the default way something displays. Everything in normal flow has a value of display, used as the default way that elements they are set on behave. For example, the fact that paragraphs in English display one below the other is due to the fact that they are styled with display: block. If you create a link around some text inside a paragraph, that link remains inline with the rest of the text, and doesn’t break onto a new line. This is because the {{htmlelement("a")}} element is display: inline by default.

+ +

You can change this default display behavior. For example, the {{htmlelement("li")}} element is display: block by default, meaning that list items display one below the other in our English document. If we change the display value to inline they now display next to each other, as words would do in a sentence. The fact that you can change the value of display for any element means that you can pick HTML elements for their semantic meaning, without being concerned about how they will look. The way they look is something that you can change.

+ +

In addition to being able to change the default presentation by turning an item from block to inline and vice versa, there are some bigger layout methods that start out as a value of display. However, when using these, you will generally need to invoke additional properties. The two values most important for our purposes when discussing layout are display: flex and display: grid.

+ +

Flexbox

+ +

Flexbox is the short name for the Flexible Box Layout Module, designed to make it easy for us to lay things out in one dimension — either as a row or as a column. To use flexbox, you apply display: flex to the parent element of the elements you want to lay out; all its direct children then become flex items. We can see this in a simple example.

+ +

The HTML markup below gives us a containing element, with a class of wrapper, inside which are three {{htmlelement("div")}} elements. By default these would display as block elements, below one another, in our English language document.

+ +

However, if we add display: flex to the parent, the three items now arrange themselves into columns. This is due to them becoming flex items and being affected by some initial values that flexbox sets on the flex container. They are displayed in a row, because the initial value of {{cssxref("flex-direction")}} set on their parent is row. They all appear to stretch to the height of the tallest item, because the initial value of the {{cssxref("align-items")}} property set on their parent is stretch. This means that the items stretch to the height of the flex container, which in this case is defined by the tallest item. The items all line up at the start of the container, leaving any extra space at the end of the row.

+ +
+ + +
.wrapper {
+  display: flex;
+}
+
+ +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three</div>
+</div>
+
+
+ +

{{ EmbedLiveSample('Flex_1', '300', '200') }}

+ +

In addition to the above properties that can be applied to the flex container, there are properties that can be applied to the flex items. These properties, among other things, can change the way that the items flex, enabling them to expand and contract to fit into the available space.

+ +

As a simple example of this, we can add the {{cssxref("flex")}} property to all of our child items, with a value of 1. This will cause all of the items to grow and fill the container, rather than leaving space at the end. If there is more space then the items will become wider; if there is less space they will become narrower. In addition, if you add another element to the markup the items will all become smaller to make space for it — they will adjust size to take up the same amount of space, whatever that is.

+ +
+ + +
.wrapper {
+    display: flex;
+}
+
+.wrapper > div {
+    flex: 1;
+}
+
+ +
<div class="wrapper">
+    <div class="box1">One</div>
+    <div class="box2">Two</div>
+    <div class="box3">Three</div>
+</div>
+
+
+ +

{{ EmbedLiveSample('Flex_2', '300', '200') }}

+ +
+

Note: This has been a very short introduction to what is possible in Flexbox, to find out more, see our Flexbox article.

+
+ +

Grid Layout

+ +

While flexbox is designed for one-dimensional layout, Grid Layout is designed for two dimensions — lining things up in rows and columns.

+ +

Once again, you can switch on Grid Layout with a specific value of display — display: grid. The below example uses similar markup to the flex example, with a container and some child elements. In addition to using display: grid, we are also defining some row and column tracks on the parent using the {{cssxref("grid-template-rows")}} and {{cssxref("grid-template-columns")}} properties respectively. We've defined three columns each of 1fr and two rows of 100px. I don’t need to put any rules on the child elements; they are automatically placed into the cells our grid has created.

+ +
+ + +
.wrapper {
+    display: grid;
+    grid-template-columns: 1fr 1fr 1fr;
+    grid-template-rows: 100px 100px;
+    grid-gap: 10px;
+}
+
+ +
<div class="wrapper">
+    <div class="box1">One</div>
+    <div class="box2">Two</div>
+    <div class="box3">Three</div>
+    <div class="box4">Four</div>
+    <div class="box5">Five</div>
+    <div class="box6">Six</div>
+</div>
+
+
+ +

{{ EmbedLiveSample('Grid_1', '300', '330') }}

+ +

Once you have a grid, you can explicitly place your items on it, rather than relying on the auto-placement behavior seen above. In the second example below we have defined the same grid, but this time with three child items. We've set the start and end line of each item using the {{cssxref("grid-column")}} and {{cssxref("grid-row")}} properties. This causes the items to span multiple tracks.

+ +
+ + +
.wrapper {
+    display: grid;
+    grid-template-columns: 1fr 1fr 1fr;
+    grid-template-rows: 100px 100px;
+    grid-gap: 10px;
+}
+
+.box1 {
+    grid-column: 2 / 4;
+    grid-row: 1;
+}
+
+.box2 {
+    grid-column: 1;
+    grid-row: 1 / 3;
+}
+
+.box3 {
+    grid-row: 2;
+    grid-column: 3;
+}
+
+ +
<div class="wrapper">
+    <div class="box1">One</div>
+    <div class="box2">Two</div>
+    <div class="box3">Three</div>
+</div>
+
+
+ +

{{ EmbedLiveSample('Grid_2', '300', '330') }}

+ +
+

Note: These two examples are just a small part of the power of Grid layout; to find out more see our Grid Layout article.

+
+ +

The rest of this guide covers other layout methods, which are less important for the main layout structures of your page but can still help you achieve specific tasks. By understanding the nature of each layout task, you will soon find that when you look at a particular component of your design the type of layout best suited to it will often be clear.

+ +

Floats

+ +

Floating an element changes the behavior of that element and the block level elements that follow it in normal flow. The element is moved to the left or right and removed from normal flow, and the surrounding content floats around the floated item.

+ +

The {{cssxref("float")}} property has four possible values:

+ + + +

In the example below we float a <div> left, and give it a {{cssxref("margin")}} on the right to push the text away from the element. This gives us the effect of text wrapped around that box, and is most of what you need to know about floats as used in modern web design.

+ +
+ + +
<h1>Simple float example</h1>
+
+<div class="box">Float</div>
+
+<p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula. Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p>
+
+
+ +
+.box {
+    float: left;
+    width: 150px;
+    height: 150px;
+    margin-right: 30px;
+}
+
+
+ +

{{ EmbedLiveSample('Float_1', '100%', 600) }}

+ +
+

Note: Floats are fully explained in our lesson on the float and clear properties. Prior to techniques such as Flexbox and Grid Layout floats were used as a method of creating column layouts. You may still come across these methods on the web; we will cover these in the lesson on legacy layout methods.

+
+ +

Positioning techniques

+ +

Positioning allows you to move an element from where it would be placed when in normal flow to another location. Positioning isn’t a method for creating your main page layouts, it is more about managing and fine-tuning the position of specific items on the page.

+ +

There are however useful techniques for certain layout patterns that rely on the {{cssxref("position")}} property. Understanding positioning also helps in understanding normal flow, and what it is to move an item out of normal flow.

+ +

There are five types of positioning you should know about:

+ + + +

Simple positioning example

+ +

To provide familiarity with these page layout techniques, we'll show you a couple of quick examples. Our examples will all feature the same HTML, which is as follows:

+ +
<h1>Positioning</h1>
+
+<p>I am a basic block level element.</p>
+<p class="positioned">I am a basic block level element.</p>
+<p>I am a basic block level element.</p>
+ +

This HTML will be styled by default using the following CSS:

+ +
body {
+  width: 500px;
+  margin: 0 auto;
+}
+
+p {
+    background-color: rgb(207,232,220);
+    border: 2px solid rgb(79,185,227);
+    padding: 10px;
+    margin: 10px;
+    border-radius: 5px;
+}
+
+ +

The rendered output is as follows:

+ +

{{ EmbedLiveSample('Simple_positioning_example', '100%', 300) }}

+ +

Relative positioning

+ +

Relative positioning allows you to offset an item from the position in normal flow it would have by default. This means you could achieve a task such as moving an icon down a bit so it lines up with a text label. To do this, we could add the following rule to add relative positioning:

+ +
.positioned {
+  position: relative;
+  top: 30px;
+  left: 30px;
+}
+ +

Here we give our middle paragraph a {{cssxref("position")}} value of relative — this doesn't do anything on its own, so we also add {{cssxref("top")}} and {{cssxref("left")}} properties. These serve to move the affected element down and to the right — this might seem like the opposite of what you were expecting, but you need to think of it as the element being pushed on its left and top sides, which result in it moving right and down.

+ +

Adding this code will give the following result:

+ +
+ + +
.positioned {
+  position: relative;
+  background: rgba(255,84,104,.3);
+  border: 2px solid rgb(255,84,104);
+  top: 30px;
+  left: 30px;
+}
+
+ +

{{ EmbedLiveSample('Relative_1', '100%', 300) }}

+ +

Absolute positioning

+ +

Absolute positioning is used to completely remove an element from normal flow, and place it using offsets from the edges of a containing block.

+ +

Going back to our original non-positioned example, we could add the following CSS rule to implement absolute positioning:

+ +
.positioned {
+  position: absolute;
+  top: 30px;
+  left: 30px;
+}
+ +

Here we give our middle paragraph a {{cssxref("position")}} value of absolute, and the same {{cssxref("top")}} and {{cssxref("left")}} properties as before. Adding this code, however, will give the following result:

+ +
+ + +
.positioned {
+    position: absolute;
+    background: rgba(255,84,104,.3);
+    border: 2px solid rgb(255,84,104);
+    top: 30px;
+    left: 30px;
+}
+
+ +

{{ EmbedLiveSample('Absolute_1', '100%', 300) }}

+ +

This is very different! The positioned element has now been completely separated from the rest of the page layout and sits over the top of it. The other two paragraphs now sit together as if their positioned sibling doesn't exist. The {{cssxref("top")}} and {{cssxref("left")}} properties have a different effect on absolutely positioned elements than they do on relatively positioned elements. In this case the offsets have been calculated from the top and left of the page. It is possible to change the parent element that becomes this container and we will take a look at that in the lesson on positioning.

+ +

Fixed positioning

+ +

Fixed positioning removes our element from document flow in the same way as absolute positioning. However, instead of the offsets being applied from the container, they are applied from the viewport. As the item remains fixed in relation to the viewport we can create effects such as a menu which remains fixed as the page scrolls beneath it.

+ +

For this example our HTML is three paragraphs of text, in order that we can cause the page to scroll, and a box to which we will give position: fixed.

+ +
<h1>Fixed positioning</h1>
+
+<div class="positioned">Fixed</div>
+
+<p>Paragraph 1.</p>
+<p>Paragraph 2.</p>
+<p>Paragraph 3.</p>
+
+ +
+ + +
.positioned {
+    position: fixed;
+    top: 30px;
+    left: 30px;
+}
+
+ +

{{ EmbedLiveSample('Fixed_1', '100%', 200) }}

+ +

Sticky positioning

+ +

Sticky positioning is the final positioning method that we have at our disposal. It mixes the default static positioning with fixed positioning. When an item has position: sticky it will scroll in normal flow until it hits offsets from the viewport that we have defined. At that point it becomes "stuck" as if it had position: fixed applied.

+ +
+ + +
.positioned {
+  position: sticky;
+  top: 30px;
+  left: 30px;
+}
+
+ +

{{ EmbedLiveSample('Sticky_1', '100%', 200) }}

+ +
+

Note: to find more out about positioning, see our Positioning article.

+
+ +

Table layout

+ +

HTML tables are fine for displaying tabular data, but many years ago — before even basic CSS was supported reliably across browsers — web developers used to also use tables for entire web page layouts — putting their headers, footers, different columns, etc. in various table rows and columns. This worked at the time, but it has many problems — table layouts are inflexible, very heavy on markup, difficult to debug, and semantically wrong (e.g., screen reader users have problems navigating table layouts).

+ +

The way that a table looks on a webpage when you use table markup is due to a set of CSS properties that define table layout. These properties can be used to lay out elements that are not tables, a use which is sometimes described as "using CSS tables".

+ +

The example below shows one such use; using CSS tables for layout should be considered a legacy method at this point, for those situations where you have very old browsers without support for Flexbox or Grid.

+ +

Let's look at an example. First, some simple markup that creates an HTML form. Each input element has a label, and we've also included a caption inside a paragraph. Each label/input pair is wrapped in a {{htmlelement("div")}}, for layout purposes.

+ +
<form>
+  <p>First of all, tell us your name and age.</p>
+  <div>
+    <label for="fname">First name:</label>
+    <input type="text" id="fname">
+  </div>
+  <div>
+    <label for="lname">Last name:</label>
+    <input type="text" id="lname">
+  </div>
+  <div>
+    <label for="age">Age:</label>
+    <input type="text" id="age">
+  </div>
+</form>
+ +

Now, the CSS for our example. Most of the CSS is fairly ordinary, except for the uses of the {{cssxref("display")}} property. The {{htmlelement("form")}}, {{htmlelement("div")}}s, and {{htmlelement("label")}}s and {{htmlelement("input")}}s have been told to display like a table, table rows, and table cells respectively — basically, they'll act like HTML table markup, causing the labels and inputs to line up nicely by default. All we then have to do is add a bit of sizing, margin, etc. to make everything look a bit nicer and we're done.

+ +

You'll notice that the caption paragraph has been given display: table-caption; — which makes it act like a table {{htmlelement("caption")}} — and caption-side: bottom; to tell the caption to sit on the bottom of the table for styling purposes, even though the markup is before the <input> elements in the source. This allows for a nice bit of flexibility.

+ +
html {
+  font-family: sans-serif;
+}
+
+form {
+  display: table;
+  margin: 0 auto;
+}
+
+form div {
+  display: table-row;
+}
+
+form label, form input {
+  display: table-cell;
+  margin-bottom: 10px;
+}
+
+form label {
+  width: 200px;
+  padding-right: 5%;
+  text-align: right;
+}
+
+form input {
+  width: 300px;
+}
+
+form p {
+  display: table-caption;
+  caption-side: bottom;
+  width: 300px;
+  color: #999;
+  font-style: italic;
+}
+ +

This gives us the following result:

+ +

{{ EmbedLiveSample('Table_layout', '100%', '170') }}

+ +

You can also see this example live at css-tables-example.html (see the source code too.)

+ +

Multi-column layout

+ +

The multi-column layout module gives us a way to lay out content in columns, similar to how text flows in a newspaper. While reading up and down columns is less useful in a web context as you don’t want to force users to scroll up and down, arranging content into columns can be a useful technique.

+ +

To turn a block into a multicol container we use either the {{cssxref("column-count")}} property, which tells the browser how many columns we would like to have, or the {{cssxref("column-width")}} property, which tells the browser to fill the container with as many columns of at least that width.

+ +

In the below example we start with a block of HTML inside a containing <div> element with a class of container.

+ +
<div class="container">
+    <h1>Multi-column layout</h1>
+
+    <p>Paragraph 1.</p>
+    <p>Paragraph 2.</p>
+
+</div>
+
+ +

We are using a column-width of 200 pixels on that container, causing the browser to create as many 200-pixel columns as will fit in the container and then share the remaining space between the created columns.

+ +
+ + +
    .container {
+        column-width: 200px;
+    }
+
+ +

{{ EmbedLiveSample('Multicol_1', '100%', 200) }}

+ +

Summary

+ +

This article has provided a brief summary of all the layout technologies you should know about. Read on for more information on each individual technology!

+ +

{{NextMenu("Learn/CSS/CSS_layout/Normal_Flow", "Learn/CSS/CSS_layout")}}

+ +

In this module

+ + diff --git a/files/pt-br/learn/css/css_layout/layout_de_varias_colunas/index.html b/files/pt-br/learn/css/css_layout/layout_de_varias_colunas/index.html new file mode 100644 index 0000000000..2605843ff4 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/layout_de_varias_colunas/index.html @@ -0,0 +1,414 @@ +--- +title: Layout de varias colunas +slug: Learn/CSS/CSS_layout/Layout_de_varias_colunas +translation_of: Learn/CSS/CSS_layout/Multiple-column_Layout +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/CSS/CSS_layout/Positioning", "Learn/CSS/CSS_layout/Responsive_Design", "Learn/CSS/CSS_layout")}}
+ +

A especificação de layout de várias colunas fornece um método de disposição do conteúdo em colunas, como você pode ver em um jornal. Este artigo explica como usar esse recurso.

+ + + + + + + + + + + + +
Pré requisitos:HTML basico (estude Introduction to HTML) e uma ideia de como CSS funciona (estude Introduction to CSS).
Objetivo: +

Aprender como criar layouts de várias colunas em paginas web, tal qual estão formatadas as paginas de um jornal.

+ + +
+ +

Um exemplo basico

+ +

Agora nós vamos explorar como usar layouts de varias colunas, frequentemente referido como multicol. Você pode começar pelo download do arquivo multicol - ponto de partida, e adicionar o CSS nos locais apropriados. Na parte inferior desta seção, você pode ver um exemplo real da aparência do código final.

+ +

Nosso ponto de partida contem um HTML simples; um invólucro com uma classe de container  dentro do qual há um cabeçalho e alguns parágrafos.

+ +

O {{htmlelement("div")}} com a classe de container se tornará nosso muticol container. Nós ativamos o multicol usando uma de duas propriedades {{cssxref("column-count")}} ou {{cssxref("column-width")}}. A propriedade column-count criará tantas colunas quanto o valor que você atribuir; portanto, se voce adicionar o seguinte CSS à sua stylesheet e recarregar a pagina, você obterá três colunas:

+ +

+

.container {
+  column-count: 3;
+}
+
+ + +

As colunas que você criar têm larguras flexíveis - o navegador calcula quanto espaço será atribuido a cada coluna.

+ +
+ + +
<div class="container">
+  <h1>Simple multicol example</h1>
+
+  <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate.
+  Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci vel, viverra egestas ligula.
+  Curabitur vehicula tellus neque, ac ornare ex malesuada et. In vitae convallis lacus. Aliquam erat volutpat. Suspendisse
+  ac imperdiet turpis. Aenean finibus sollicitudin eros pharetra congue. Duis ornare egestas augue ut luctus. Proin blandit
+  quam nec lacus varius commodo et a urna. Ut id ornare felis, eget fermentum sapien.</p>
+
+  <p>Nam vulputate diam nec tempor bibendum. Donec luctus augue eget malesuada ultrices. Phasellus turpis est, posuere sit amet dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique
+  elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit
+  cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque penatibus et magnis
+  dis parturient montes, nascetur ridiculus mus.</p>
+</div>
+
+ +
.container {
+  column-count: 3;
+}
+
+
+ +

{{ EmbedLiveSample('Multicol_1', '100%', 400) }}

+ +

Mude o seu CSS para usar column-width, como a seguir:

+ +
.container {
+  column-width: 200px;
+}
+
+ +

O navegador agora fornecerá o maior número possível de colunas, do tamanho que você especificar; qualquer espaço restante é compartilhado entre as colunas existentes. Isso significa que você não terá exatamente a largura que especificar, a menos que seu container seja exatamente divisível por essa largura.

+ +
+ + +
.container {
+  column-width: 200px;
+}
+
+
+ +

{{ EmbedLiveSample('Multicol_2', '100%', 400) }}

+ +

Styling the columns

+ +

The columns created by multicol cannot be styled individually. There is no way to make one column bigger than other columns, or to change the background or text color of a single column. You have two opportunities to change the way that columns display:

+ + + +

Using your example above, change the size of the gap by adding a column-gap property:

+ +
.container {
+  column-width: 200px;
+  column-gap: 20px;
+}
+ +

You can play around with different values — the property accepts any length unit. Now add a rule between the columns, with column-rule. In a similar way to the {{cssxref("border")}} property that you encountered in previous lessons, column-rule is a shorthand for {{cssxref("column-rule-color")}}, {{cssxref("column-rule-style")}}, and {{cssxref("column-rule-width")}}, and accepts the same values as border.

+ +
.container {
+  column-count: 3;
+  column-gap: 20px;
+  column-rule: 4px dotted rgb(79, 185, 227);
+}
+ +

Try adding rules of different styles and colors.

+ +
+ +
+ +

{{ EmbedLiveSample('Multicol_3', '100%', 400) }}

+ +

Something to take note of is that the rule does not take up any width of its own. It lies across the gap you created with column-gap. To make more space either side of the rule you will need to increase the column-gap size.

+ +

Columns and fragmentation

+ +

The content of a multi-column layout is fragmented. It essentially behaves the same way as content behaves in paged media — such as when you print a webpage. When you turn your content into a multicol container it is fragmented into columns, and the content breaks to allow this to happen.

+ +

Sometimes, this breaking will happen in places that lead to a poor reading experience. In the live example below, I have used multicol to lay out a series of boxes, each of which have a heading and some text inside. The heading becomes separated from the text if the columns fragment between the two.

+ +
+ + +
<div class="container">
+    <div class="card">
+      <h2>I am the heading</h2>
+      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat
+                vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies
+                tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci
+                vel, viverra egestas ligula.</p>
+    </div>
+
+    <div class="card">
+      <h2>I am the heading</h2>
+      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat
+                vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies
+                tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci
+                vel, viverra egestas ligula.</p>
+    </div>
+
+    <div class="card">
+      <h2>I am the heading</h2>
+      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat
+                vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies
+                tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci
+                vel, viverra egestas ligula.</p>
+    </div>
+    <div class="card">
+      <h2>I am the heading</h2>
+      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat
+                vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies
+                tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci
+                vel, viverra egestas ligula.</p>
+    </div>
+
+    <div class="card">
+      <h2>I am the heading</h2>
+      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat
+                vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies
+                tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci
+                vel, viverra egestas ligula.</p>
+    </div>
+
+    <div class="card">
+      <h2>I am the heading</h2>
+      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat
+                vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies
+                tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci
+                vel, viverra egestas ligula.</p>
+    </div>
+
+    <div class="card">
+      <h2>I am the heading</h2>
+      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat
+                vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies
+                tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ipsum, tristique sit amet orci
+                vel, viverra egestas ligula.</p>
+    </div>
+
+</div>
+
+ +
.container {
+  column-width: 250px;
+  column-gap: 20px;
+}
+
+.card {
+  background-color: rgb(207, 232, 220);
+  border: 2px solid rgb(79, 185, 227);
+  padding: 10px;
+  margin: 0 0 1em 0;
+}
+
+ +

{{ EmbedLiveSample('Multicol_4', '100%', 600) }}

+ +

To control this behavior we can use properties from the CSS Fragmentation specification. This specification gives us properties to control breaking of content in multicol and in paged media. For example, add the property {{cssxref("break-inside")}} with a value of avoid to the rules for .card. This is the container of the heading and text, and therefore we do not want to fragment this box.

+ +

At the present time it is also worth adding the older property page-break-inside: avoid for best browser support.

+ +
.card {
+  break-inside: avoid;
+  page-break-inside: avoid;
+  background-color: rgb(207,232,220);
+  border: 2px solid rgb(79,185,227);
+  padding: 10px;
+  margin: 0 0 1em 0;
+}
+
+ +

Reload the page and your boxes should stay in one piece.

+ +
+ + +
.container {
+  column-width: 250px;
+  column-gap: 20px;
+}
+
+.card {
+  break-inside: avoid;
+  page-break-inside: avoid;
+  background-color: rgb(207, 232, 220);
+  border: 2px solid rgb(79, 185, 227);
+  padding: 10px;
+  margin: 0 0 1em 0;
+}
+
+ +

{{ EmbedLiveSample('Multicol_5', '100%', 600) }}

+ +

Summary

+ +

You now know how to use the basic features of multiple-column layout, another tool at your disposal when choosing a layout method for the designs you are building.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/CSS/CSS_layout/Positioning", "Learn/CSS/CSS_layout/Responsive_Design", "Learn/CSS/CSS_layout")}}

+ +

In this module

+ + diff --git a/files/pt-br/learn/css/css_layout/positioning/index.html b/files/pt-br/learn/css/css_layout/positioning/index.html new file mode 100644 index 0000000000..51a024e875 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/positioning/index.html @@ -0,0 +1,574 @@ +--- +title: Positioning +slug: Learn/CSS/CSS_layout/Positioning +translation_of: Learn/CSS/CSS_layout/Positioning +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Aprenda/CSS/CSS_layout/Floats", "Aprenda/CSS/CSS_layout/Multiple-column_Layout", "Aprenda/CSS/CSS_layout")}}
+ +

Positioning allows you to take elements out of the normal document layout flow, and make them behave differently; for example sitting on top of one another, or always remaining in the same place inside the browser viewport. This article explains the different {{cssxref("position")}} values, and how to use them.

+ + + + + + + + + + + + +
Prerequisites:HTML basics (study Introduction to HTML), and an idea of How CSS works (study Introduction to CSS.)
Objective:To learn how CSS positioning works.
+ +

We'd like you to follow along with the exercises on your local computer, if possible — grab a copy of 0_basic-flow.html from our GitHub repo (source code here) and use that as a starting point.

+ +

Introducing positioning

+ +

The whole idea of positioning is to allow us to override the basic document flow behavior described above, to produce interesting effects. What if you want to slightly alter the position of some boxes inside a layout from their default layout flow position, to give a slightly quirky, distressed feel? Positioning is your tool. Or if you want to create a UI element that floats over the top of other parts of the page, and/or always sits in the same place inside the browser window no matter how much the page is scrolled? Positioning makes such layout work possible.

+ +

There are a number of different types of positioning that you can put into effect on HTML elements. To make a specific type of positioning active on an element, we use the {{cssxref("position")}} property.

+ +

Static positioning

+ +

Static positioning is the default that every element gets — it just means "put the element into its normal position in the document layout flow — nothing special to see here."

+ +

To demonstrate this, and get your example set up for future sections, first add a class of positioned to the second {{htmlelement("p")}} in the HTML:

+ +
<p class="positioned"> ... </p>
+ +

Now add the following rule to the bottom of your CSS:

+ +
.positioned {
+  position: static;
+  background: yellow;
+}
+ +

If you now save and refresh, you'll see no difference at all, except for the updated background color of the 2nd paragraph. This is fine — as we said before, static positioning is the default behavior!

+ +
+

Note: You can see the example at this point live at 1_static-positioning.html (see source code).

+
+ +

Relative positioning

+ +

Relative positioning is the first position type we'll take a look at. This is very similar to static positioning, except that once the positioned element has taken its place in the normal layout flow, you can then modify its final position, including making it overlap other elements on the page. Go ahead and update the position declaration in your code:

+ +
position: relative;
+ +

If you save and refresh at this stage, you won't see a change in the result at all.  So how do you modify the element's position? You need to use the {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} properties, which we'll explain in the next section.

+ +

Introducing top, bottom, left, and right

+ +

{{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} are used alongside {{cssxref("position")}} to specify exactly where to move the positioned element to. To try this out, add the following declarations to the .positioned rule in your CSS:

+ +
top: 30px;
+left: 30px;
+ +
+

Note: The values of these properties can take any units you'd logically expect — pixels, mm, rems, %, etc.

+
+ +

If you now save and refresh, you'll get a result something like this:

+ + + +

{{ EmbedLiveSample('Introducing_top_bottom_left_and_right', '100%', 500) }}

+ +

Cool, huh? Ok, so this probably wasn't what you were expecting — why has it moved to the bottom and right if we specified top and left? Illogical as it may initially sound, this is just the way that relative positioning works — you need to think of an invisible force that pushes the specified side of the positioned box, moving it in the opposite direction. So for example, if you specify top: 30px;, a force pushes the top of the box, causing it to move downwards by 30px.

+ +
+

Note: You can see the example at this point live at 2_relative-positioning.html (see source code).

+
+ +

Absolute positioning

+ +

Absolute positioning brings very different results. Let's try changing the position declaration in your code as follows:

+ +
position: absolute;
+ +

If you now save and refresh, you should see something like so:

+ + + +

{{ EmbedLiveSample('Absolute_positioning', '100%', 420) }}

+ +

First of all, note that the gap where the positioned element should be in the document flow is no longer there — the first and third elements have closed together like it no longer exists! Well, in a way, this is true. An absolutely positioned element no longer exists in the normal document layout flow. Instead, it sits on its own layer separate from everything else. This is very useful: it means that we can create isolated UI features that don't interfere with the position of other elements on the page.  For example, popup information boxes and control menus; rollover panels; UI features that can be dragged and dropped anywhere on the page; and so on...

+ +

Second, notice that the position of the element has changed — this is because {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} behave in a different way with absolute positioning. Instead of specifying the direction the element should move in, they specify the distance the element should be from each containing element's sides. So in this case, we are saying that the absolutely positioned element should sit 30px from the top of the "containing element", and 30px from the left.

+ +
+

Note: You can use {{cssxref("top")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("right")}} to resize elements if you need to. Try setting top: 0; bottom: 0; left: 0; right: 0; and margin: 0; on your positioned elements and see what happens! Put it back again afterwards...

+
+ +
+

Note: Yes, margins still affect positioned elements. Margin collapsing doesn't, however.

+
+ +
+

Note: You can see the example at this point live at 3_absolute-positioning.html (see source code).

+
+ +

Positioning contexts

+ +

Which element is the "containing element" of an absolutely positioned element? This is very much dependent on the position property of the ancestors of the positioned element (See Identifying the containing block). 

+ +

If no ancestor elements have their position property explicitly defined, then by default all ancestor elements will have a static position. The result of this is, the absolutely positioned element will be contained in the initial containing block. The initial containing block has the dimensions of the viewport, and is also the block that contains the {{htmlelement("html")}} element. Simply put, the absolutely positioned element will be contained outside of the {{htmlelement("html")}} element, and be positioned relative to the initial viewport. 

+ +

The positioned element is nested inside the {{htmlelement("body")}} in the HTML source, but in the final layout, it is 30px away from the top and left of the edge of the page. We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors — to one of the elements it is nested inside (you can't position it relative to an element it is not nested inside). To demonstrate this, add the following declaration to your body rule:

+ +
position: relative;
+ +

This should give the following result:

+ + + +

{{ EmbedLiveSample('Positioning_contexts', '100%', 420) }}

+ +

The positioned element now sits relative to the {{htmlelement("body")}} element.

+ +
+

Note: You can see the example at this point live at 4_positioning-context.html (see source code).

+
+ +

Introducing z-index

+ +

All this absolute positioning is good fun, but there is another thing we haven't considered yet — when elements start to overlap, what determines which elements appear on top of which other elements? In the example we've seen so far, we only have one positioned element in the positioning context, and it appears on the top, since positioned elements win over non-positioned elements. What about when we have more than one?

+ +

Try adding the following to your CSS, to make the first paragraph absolutely positioned too:

+ +
p:nth-of-type(1) {
+  position: absolute;
+  background: lime;
+  top: 10px;
+  right: 30px;
+}
+ +

At this point you'll see the first paragraph colored lime, moved out of the document flow, and positioned a bit above from where it originally was. It is also stacked below the original .positioned paragraph, where the two overlap. This is because the .positioned paragraph is the second paragraph in the source order, and positioned elements later in the source order win over positioned elements earlier in the source order.

+ +

Can you change the stacking order? Yes, you can, by using the {{cssxref("z-index")}} property. "z-index" is a reference to the z-axis. You may recall from previous points in the course where we discussed web pages using horizontal (x-axis) and vertical (y-axis) coordinates to work out positioning for things like background images and drop shadow offsets. (0,0) is at the top left of the page (or element), and the x- and y-axes run across to the right and down the page (for left to right languages, anyway.)

+ +

Web pages also have a z-axis: an imaginary line that runs from the surface of your screen, towards your face (or whatever else you like to have in front of the screen). {{cssxref("z-index")}} values affect where positioned elements sit on that axis; positive values move them higher up the stack, and negative values move them lower down the stack. By default, positioned elements all have a z-index of auto, which is effectively 0.

+ +

To change the stacking order, try adding the following declaration to your p:nth-of-type(1) rule:

+ +
z-index: 1;
+ +

You should now see the finished example, with the lime paragraph on top:

+ + + +

{{ EmbedLiveSample('Introducing_z-index', '100%', 400) }}

+ +

Note that z-index only accepts unitless index values; you can't specify that you want one element to be 23 pixels up the Z-axis — it doesn't work like that. Higher values will go above lower values, and it is up to you what values you use. Using 2 and 3 would give the same effect as 300 and 40000.

+ +
+

Note: You can see the example at this point live at 5_z-index.html (see source code).

+
+ +

Fixed positioning

+ +

Let's now look at fixed positioning. This works in exactly the same way as absolute positioning, with one key difference: whereas absolute positioning fixes an element in place relative to the {{htmlelement("html")}} element or its nearest positioned ancestor, fixed positioning fixes an element in place relative to the browser viewport itself. This means that you can create useful UI items that are fixed in place, like persisting navigation menus.

+ +

Let's put together a simple example to show what we mean. First of all, delete the existing p:nth-of-type(1) and .positioned rules from your CSS.

+ +

Now, update the body rule to remove the position: relative; declaration and add a fixed height, like so:

+ +
body {
+  width: 500px;
+  height: 1400px;
+  margin: 0 auto;
+}
+ +

Now we're going to give the {{htmlelement("h1")}} element position: fixed;, and get it to sit at the top center of the viewport. Add the following rule to your CSS:

+ +
h1 {
+  position: fixed;
+  top: 0;
+  width: 500px;
+  margin: 0 auto;
+  background: white;
+  padding: 10px;
+}
+ +

The top: 0; is required to make it stick to the top of the screen; we then give the heading the same width as the content column and use the faithful old margin: 0 auto; trick to center it. We then give it a white background and some padding, so the content won't be visible underneath it.

+ +

If you save and refresh now, you'll see a fun little effect whereby the heading stays fixed, and the content appears to scroll up and disappear underneath it. But we could improve this more — at the moment some of the content starts off underneath the heading. This is because the positioned heading no longer appears in the document flow, so the rest of the content moves up to the top. We need to move it all down a bit; we can do this by setting some top margin on the first paragraph. Add this now:

+ +
p:nth-of-type(1) {
+  margin-top: 60px;
+}
+ +

You should now see the finished example:

+ + + +

{{ EmbedLiveSample('Fixed_positioning', '100%', 400) }}

+ +
+

Note: You can see the example at this point live at 6_fixed-positioning.html (see source code).

+
+ +

position: sticky

+ +

There is another position value available called position: sticky, which is somewhat newer than the others. This is basically a hybrid between relative and fixed position, which allows a positioned element to act like it is relatively positioned until it is scrolled to a certain threshold point (e.g. 10px from the top of the viewport), after which it becomes fixed. This can be used to for example cause a navigation bar to scroll with the page until a certain point, and then stick to the top of the page. 

+ +
+ + +
.positioned {
+  position: sticky;
+  top: 30px;
+  left: 30px;
+}
+
+ +

{{ EmbedLiveSample('Sticky_1', '100%', 200) }}

+ +

An interesting and common use of position: sticky is to create a scrolling index page where different headings stick to the top of the page as they reach it. The markup for such an example might look like so:

+ +
<h1>Sticky positioning</h1>
+
+<dl>
+    <dt>A</dt>
+    <dd>Apple</dd>
+    <dd>Ant</dd>
+    <dd>Altimeter</dd>
+    <dd>Airplane</dd>
+    <dt>B</dt>
+    <dd>Bird</dd>
+    <dd>Buzzard</dd>
+    <dd>Bee</dd>
+    <dd>Banana</dd>
+    <dd>Beanstalk</dd>
+    <dt>C</dt>
+    <dd>Calculator</dd>
+    <dd>Cane</dd>
+    <dd>Camera</dd>
+    <dd>Camel</dd>
+    <dt>D</dt>
+    <dd>Duck</dd>
+    <dd>Dime</dd>
+    <dd>Dipstick</dd>
+    <dd>Drone</dd>
+    <dt>E</dt>
+    <dd>Egg</dd>
+    <dd>Elephant</dd>
+    <dd>Egret</dd>
+</dl>
+
+ +

The CSS might look as follows. In normal flow the {{htmlelement("dt")}} elements will scroll with the content. When we add position: sticky to the {{htmlelement("dt")}} element, along with a {{cssxref("top")}} value of 0, supporting browsers will stick the headings to the top of the viewport as they reach that position. Each subsequent header will then replace the previous one as it scrolls up to that position.

+ +
dt {
+  background-color: black;
+  color: white;
+  padding: 10px;
+  position: sticky;
+  top: 0;
+  left: 0;
+  margin: 1em 0;
+}
+
+ +
+ +
+ +

{{ EmbedLiveSample('Sticky_2', '100%', 200) }}

+ +
+

Note: You can see this example live at 7_sticky-positioning.html (see source code).

+
+ +

Summary

+ +

I'm sure you had fun playing with basic positioning; while it is not a method you would use for entire layouts, as you can see there are many tasks it is suited for.

+ +

{{PreviousMenuNext("Learn/CSS/CSS_layout/Floats", "Learn/CSS/CSS_layout/Multiple-column_Layout", "Learn/CSS/CSS_layout")}}

+ +

See also

+ + + +

In this module

+ + diff --git a/files/pt-br/learn/css/css_layout/responsive_design/index.html b/files/pt-br/learn/css/css_layout/responsive_design/index.html new file mode 100644 index 0000000000..bc554e4537 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/responsive_design/index.html @@ -0,0 +1,324 @@ +--- +title: Design Responsivo +slug: Learn/CSS/CSS_layout/Responsive_Design +translation_of: Learn/CSS/CSS_layout/Responsive_Design +--- +
{{learnsidebar}}{{PreviousMenuNext("Learn/CSS/CSS_layout/Multiple-column_Layout", "Learn/CSS/CSS_layout/Media_queries", "Learn/CSS/CSS_layout")}}
+ +

Nos primórdios do web design, páginas eram criadas para serem visualizadas em um tamanho de tela específico.  Se o usuário tivesse uma tela maior ou menor do que o esperado, os resultados iam de barras de rolagem indesejadas, tamanhos de linha excessivamente longos e uso inadequado do espaço. À medida que diferentes tamanhos de tela foram aparecendo, surgiu o conceito de web design responsivo (RWD), um conjunto de práticas que permite que páginas da Web alterem seu layout e aparência para se adequarem a diferentes larguras, resoluções, etc. É uma ideia que mudou a forma de como projetamos para a Web com múltiplos dispositivos e, neste artigo, ajudaremos você a entender as principais técnicas que você precisa conhecer para dominá-la.

+ + + + + + + + + + + + +
Prerrequisitos:HTML básico (estude Introduction to HTML), e uma idea de como o CSS funciona (estude CSS first steps e CSS building blocks.)
Objetivo:Entender os conceitos fundamentais e a história do design responsivo.
+ +

História dos layouts de sites

+ +

Em algum ponto da história, você tinha duas opções ao criar um site:

+ + + +

Essas duas abordagens, geralmente, resultavam em um site com a melhor aparência na tela da pessoa que o projetava! O site líquido resultou em um design esmagado para telas menores (como visto abaixo) e comprimentos de linha muito longos em telas maiores.

+ +
A layout with two columns squashed into a mobile size viewport. +
+
+ +
+

Nota: Veja este layout líquido simples: exemplo, código-fonte. Ao visualizar o exemplo, arraste a janela do navegador para dentro e para fora para ver como isso fica em tamanhos diferentes.

+
+ +

O site de largura fixa criava uma barra de rolagem horizontal em telas menores que a largura do site (como mostrado abaixo) e muito espaço em branco nas bordas do design em telas maiores.

+ +
A layout with a horizontal scrollbar in a mobile viewport. +
+
+ +
+

Nota: Veja este layout simples de largura fixa: exemplo, código-fonte. Observe novamente o resultado ao alterar o tamanho da janela do navegador.

+
+ +
+

Nota: As capturas de tela acima foram tiradas usando o Responsive Design Mode no Firefox DevTools.

+
+ +

À medida que a Web para dispositivos móveis começava a se tornar realidade com os primeiros telefones com essas características, empresas que desejavam adotar os dispositivos móveis geralmente criavam uma versão mobile do seu site, com uma URL diferente (geralmente algo como m.exemplo.com ou exemplo.mobi) Isso significava que duas versões separadas do site tinham que ser desenvolvidas e mantidas atualizadas.

+ +

Além disso, esses sites para celular geralmente ofereciam uma experiência muito restrita. À medida que os dispositivos móveis se tornaram mais poderosos e capazes de exibir sites completos, os usuários de celular ficaram frustrados, pois, se viram presos na versão mobile do site e incapazes de acessar todas as informações que faziam parte da versão para desktop.

+ +

Layouts flexiveis antes do design responsivo

+ +

Várias abordagens foram desenvolvidas para tentar resolver as desvantagens dos métodos de largura líquida ou largura fixa da construção de sites. Em 2004, Cameron Adams escreveu um artigo intitulado Resolution dependent layout, descrevendo um método para criar um design que pudesse se adaptar a diferentes resoluções de tela. Essa abordagem necessitava do JavaScript para detectar a resolução da tela e carregar o CSS correto.

+ +

Zoe Mickley Gillenwater foi fundamental no seu trabalho de descrever e formalizar as diferentes maneiras pelas quais sites flexíveis poderiam ser criados, tentando encontrar um meio termo entre preencher a tela ou ter tamanho completamente fixo.

+ +

Design Responsivo

+ +

O termo design responsivo foi cunhado por Ethan Marcotte em 2010, e descreveu o uso de três técnicas combinadas.

+ +
    +
  1. A primeira foi a ideia de grids fluidas, que já estava sendo explorada por Gillenwater, e pode ser encontrada no artigo de Marcotte, Fluid Grids (publicado em 2009 em A List Apart).
  2. +
  3. A segunda técnica foi a ideia de imagens fluidas. Usando uma técnica muito simples que setava a propriedade max-width com 100%, as imagens seriam reduzidas se a coluna que as continha se tornasse mais estreita que o tamanho intrínseco da imagem, mas nunca aumentariam. Isso permitiu que uma imagem fosse reduzida em tamanho para caber em uma coluna de tamanho flexível, em vez de transbordar, mas não aumentava e nem tornava-se pixelizada se a coluna fosse mais larga que a imagem.
  4. +
  5. O terceiro componente-chave foi a media query. Media Queries habilitavam o tipo de opção de layout usando o JavaScript, que Cameron Adams havia explorado anteriormente, usando apenas CSS. Em vez de ter um layout para todos os tamanhos de tela, o layout podia ser alterado. As barras laterais podiam ser reposicionadas para a tela menor ou uma navegação alternativa podia ser exibida.
  6. +
+ +

É importante entender que o design responsivo não é uma tecnologia separada — é um termo usado para descrever uma abordagem ao web design, ou um conjunto de melhores práticas, usado para criar um layout que possa responder ao dispositivo que está sendo usado para visualizar o conteúdo. Na exploração original de Marcotte, isso significava grades flexíveis (usando floats) e media queries, no entanto, nos últimos 10 anos, desde que o artigo foi escrito, trabalhar de forma responsiva se tornou um padrão. Os métodos de layout CSS modernos são inerentemente responsivos, e temos coisas novas incorporadas à plataforma web para facilitar o design de sites responsivos.

+ +

O restante deste artigo indicará os vários recursos da plataforma web que você pode usar ao criar um site responsivo.

+ +

Media Queries

+ +

O Design Responsivo apenas foi capaz de emergir devido o recurse de media query. A especificação Media Queries Level 3 se tornou uma Recomendação de Candidato em 2009, significando que estava pronto para ser implementado nos browsers. Media Queries nos permitem executar uma série de testes (e.g. se a tela do usuário é maior que uma certa largura, ou uma certa resolução)  e aplicar um CSS seletivamente para estilizar a página de acordo com as necessidades do usuário.

+ +

Por exemplo, a seguinte media querie testa se a página atual está sendo exibida como mídia de tela (portanto, não é um documento impresso) e o viewport tem pelo menos 800 pixels de largura. O CSS para o seletor .container será aplicado apenas se essas duas condições forem verdade.

+ +
@media screen and (min-width: 800px) {
+  .container {
+    margin: 1em 2em;
+  }
+} 
+
+ +

Você pode adicionar múltiplos media queries dentro de uma folha de de estilo, ajustando inteiramente seu layout ou partes dele que melhor se adequem a vários tamanhos de tela. Os pontos em quem uma Media Query é introduzida e o layout alterado são conhecidos como breakpoints.

+ +

Uma abordagem comum ao utilizar Media Queries é criar um layout de única coluna para dispositivos de telas pequenas (e.g smartphones), então fazer a checagem para telas maiores e implementar um layout de múltiplas colunas quando houver largura suficiente. Esse design é frequentemente descrito como mobile first.

+ +

Encontre mais detalhes na documentação MDN para Media Queries.

+ +

Grids Flexíveis

+ +

Sites responsivos não apenas mudam seu layout entre breakpoints, eles são construídos em grids flexíveis. Um grid flexível significa que não há necessidade de marcar todos os tamanhos possíveis existentes, e sim, construir um layout perfeito baseado em pixels que se adequa automaticamente à tela. Essa abordagem seria impossível dado o vasto número de dispositivos com tamanhos diferentes que existem e o fato de que, mesmo nos desktops, as pessoas nem sempre utilizam a janela do navegador maximizada.

+ +

Com o uso de um grid flexível, não há necessidade de adicionar um breakpoint e alterar o desing no ponto onde o conteúdo começa a parecer ruim em determinada tela. Por exemplo, se o comprimento da linha se torna ilegível à medida que o tamanho da tela aumenta, ou uma caixa se fica espremida com duas palavras em cada linha, conforme o tamanho diminui.

+ +

Nos primórdios do design responsivo a única opção disponível para realizar layouts era utilizando floats. Layouts flexíveis flutuantes eram alcançados dando a cada elemento uma largura percentual, garantindo que em todo layout os totais não fossem maior que 100%. In his original piece on fluid grids, Marcotte detailed a formula for taking a layout designed using pixels and converting it into percentages.

+ +
target / context = result 
+
+ +

For example if our target column size is 60 pixels, and the context (or container) it is in is 960 pixels, we divide 60 by 960 to get a value we can use in our CSS, after moving the decimal point two places to the right.

+ +
.col {
+  width: 6.25%; /* 60 / 960 = 0.0625 */
+} 
+
+ +

This approach will be found in many places across the web today, and it is documented here in the layout section of our Legacy layout methods article. It is likely that you will come across websites using this approach in your work, so it is worth understanding it, even though you would not build a modern site using a float-based flexible grid.

+ +

The following example demonstrates a simple responsive design using Media Queries and a flexible grid. On narrow screens the layout displays the boxes stacked on top of one another:

+ +
A mobile view of the layout with boxes stacked on top of each other vertically. +

On wider screens they move to two columns:

+ +
+
+ +
A desktop view of a layout with two columns. +
+
+ +
+

Note: You can find the live example and source code for this example on GitHub.

+
+ +

Modern layout technologies

+ +

Modern layout methods such as Multiple-column layout, Flexbox, and Grid are responsive by default. They all assume that you are trying to create a flexible grid and give you easier ways to do so.

+ +

Multicol

+ +

The oldest of these layout methods is multicol — when you specify a column-count, this indicates how many columns you want your content to be split into. The browser then works out the size of these, a size that will change according to the screen size.

+ +
.container {
+  column-count: 3;
+} 
+
+ +

If you instead specify a column-width, you are specifying a minimum width. The browser will create as many columns of that width as will comfortably fit into the container, then share out the remaining space between all the columns. Therefore the number of columns will change according to how much space there is.

+ +
.container {
+  column-width: 10em;
+} 
+
+ +

Flexbox

+ +

In Flexbox, flex items will shrink and distribute space between the items according to the space in their container, as their initial behavior. By changing the values for flex-grow and flex-shrink you can indicate how you want the items to behave when they encounter more or less space around them.

+ +

In the example below the flex items will each take an equal amount of space in the flex container, using the shorthand of flex: 1 as described in the layout topic Flexbox: Flexible sizing of flex items.

+ +
.container {
+  display: flex;
+}
+
+.item {
+  flex: 1;
+} 
+
+ +
+

Note: As an example we have rebuilt the simple responsive layout above, this time using flexbox. You can see how we no longer need to use strange percentage values to calculate the size of the columns: example, source code.

+
+ +

CSS grid

+ +

In CSS Grid Layout the fr unit allows the distribution of available space across grid tracks. The next example creates a grid container with three tracks sized at 1fr. This will create three column tracks, each taking one part of the available space in the container. You can find out more about this approach to create a grid in the Learn Layout Grids topic, under Flexible grids with the fr unit.

+ +
.container {
+  display: grid;
+  grid-template-columns: 1fr 1fr 1fr;
+} 
+
+ +
+

Note: The grid layout version is even simpler as we can define the columns on the .wrapper: example, source code.

+
+ +

Responsive images

+ +

The simplest approach to responsive images was as described in Marcotte's early articles on responsive design. Basically, you would take an image that was at the largest size that might be needed, and scale it down. This is still an approach used today, and in most stylesheets you will find the following CSS somewhere:

+ +
img {
+  max-width: 100%:
+} 
+
+ +

There are obvious downsides to this approach. The image might be displayed a lot smaller than its intrinsic size, which is a waste of bandwidth — a mobile user may be downloading an image several times the size of what they actually see in the browser window. In addition, you may not want the same image aspect ratio on mobile as on desktop. For example, it might be nice to have a square image for mobile, but show the same scene as a landscape image on desktop. Or, acknowledging the smaller size of an image on mobile you might want to show a different image altogether, one which is more easily understood at a small screen size. These things can't be achieved by simply scaling down an image.

+ +

Responsive Images, using the <picture> element and the <img> srcset and sizes attributes solve both of these problems. You can provide multiple sizes along with "hints" (meta data that describes the screen size and resolution the image is best suited for), and the browser will choose the most appropriate image for each device, ensuring that a user will download an image size appropriate for the device they are using.

+ +

You can also art direct images used at different sizes, thus providing a different crop or completely different image to different screen sizes.

+ +

You can find a detailed guide to Responsive Images in the Learn HTML section here on MDN.

+ +

Responsive typography

+ +

An element of responsive design not covered in earlier work was the idea of responsive typography. Essentially, this describes changing font sizes within media queries to reflect lesser or greater amounts of screen real estate.

+ +

In this example, we want to set our level 1 heading to be 4rem, meaning it will be four times our base font size. That's a really large heading! We only want this jumbo heading on larger screen sizes, therefore we first create a smaller heading then use media queries to overwrite it with the larger size if we know that the user has a screen size of at least 1200px.

+ +
html {
+  font-size: 1em;
+}
+
+h1 {
+  font-size: 2rem;
+}
+
+@media (min-width: 1200px) {
+  h1 {
+    font-size: 4rem;
+  }
+} 
+
+ +

We have edited our responsive grid example above to also include responsive type using the method outlined. You can see how the heading switches sizes as the layout goes to the two column version.

+ +

On mobile the heading is smaller:

+ +
A stacked layout with a small heading size. +

On desktop however we see the larger heading size:

+ +
+
+ +
A two column layout with a large heading. +
+
+ +
+

Note: See this example in action: example, source code.

+
+ +

As this approach to typography shows, you do not need to restrict media queries to only changing the layout of the page. They can be used to tweak any element to make it more usable or attractive at alternate screen sizes.

+ +

Using viewport units for responsive typography

+ +

An interesting approach is to use the viewport unit vw to enable responsive typography. 1vw is equal to one percent of the viewport width, meaning that if you set your font size using vw, it will always relate to the size of the viewport.

+ +
h1 {
+  font-size: 6vw;
+}
+ +

The problem with doing the above is that the user loses the ability to zoom any text set using the vw unit, as that text is always related to the size of the viewport. Therefore you should never set text using viewport units alone.

+ +

There is a solution, and it involves using calc(). If you add the vw unit to a value set using a fixed size such as ems or rems then the text will still be zoomable. Essentially, the vw unit adds on top of that zoomed value:

+ +
h1 {
+  font-size: calc(1.5rem + 3vw);
+}
+ +

This means that we only need to specify the font size for the heading once, rather than set it up for mobile and redefine it in the media queries. The font then gradually increases as you increase the size of the viewport.

+ +
+

See an example of this in action: example, source code.

+
+ +

The viewport meta tag

+ +

If you look at the HTML source of a responsive page, you will usually see the following {{htmlelement("meta")}} tag in the <head> of the document.

+ +
<meta name="viewport" content="width=device-width,initial-scale=1">
+
+ +

This meta tag tells mobile browsers that they should set the width of the viewport to the device width, and scale the document to 100% of its intended size, which shows the document at the mobile-optimized size that you intended.

+ +

Why is this needed? Because mobile browsers tend to lie about their viewport width.

+ +

This meta tag exists because when the original iPhone launched and people started to view websites on a small phone screen, most sites were not mobile optimized. The mobile browser would therefore set the viewport width to 960 pixels, render the page at that width, and show the result as a zoomed-out version of the desktop layout. Other mobile browsers (e.g. on Google Android) did the same thing. Users could zoom in and pan around the website to view the bits they were interested in, but it looked bad. You will still see this today if you have the misfortune to come across a site that does not have a responsive design.

+ +

The trouble is that your responsive design with breakpoints and media queries won't work as intended on mobile browsers. If you've got a narrow screen layout that kicks in at 480px viewport width or less, and the viewport is set at 960px, you'll never see your narrow screen layout on mobile. By setting width=device-width you are overriding Apple's default width=960px with the actual width of the device, so your media queries will work as intended.

+ +

So you should always include the above line of HTML in the head of your documents.

+ +

There are other settings you can use with the viewport meta tag, however in general the above line is what you will want to use.

+ + + +

You should avoid using minimum-scale, maximum-scale, and in particular setting user-scalable to no. Users should be allowed to zoom as much or as little as they need to; preventing this causes accessibility problems.

+ +
+

Note: There is a CSS @ rule designed to replace the viewport meta tag — @viewport — however it has poor browser support. It was implemented in Internet Explorer and Edge, however once the Chromium-based Edge ships it will no longer be part of the Edge browser.

+
+ +

Summary

+ +

Responsive design refers to a site or application design that responds to the environment in which it is viewed. It encompasses a number of CSS and HTML features and techniques, and is now essentially just how we build websites by default. Consider the sites that you visit on your phone — it is probably fairly unusual to come across a site that is the desktop version scaled down, or where you need to scroll sideways to find things. This is because the web has moved to this approach of designing responsively.

+ +

It has also become much easier to achieve responsive designs with the help of the layout methods you have learned in these lessons. If you are new to web development today you have many more tools at your disposal than in the early days of responsive design. It is therefore worth checking the age of any materials you are referencing. While the historical articles are still useful, modern use of CSS and HTML makes it far easier to create elegant and useful designs, no matter what device your visitor views the site with.

+ +

{{PreviousMenuNext("Learn/CSS/CSS_layout/Multiple-column_Layout", "Learn/CSS/CSS_layout/Media_queries", "Learn/CSS/CSS_layout")}}

+ +

In this module

+ + diff --git a/files/pt-br/learn/css/first_steps/como_css_e_estruturado/index.html b/files/pt-br/learn/css/first_steps/como_css_e_estruturado/index.html new file mode 100644 index 0000000000..4084647920 --- /dev/null +++ b/files/pt-br/learn/css/first_steps/como_css_e_estruturado/index.html @@ -0,0 +1,502 @@ +--- +title: Como CSS é estruturado +slug: Learn/CSS/First_steps/Como_CSS_e_estruturado +translation_of: Learn/CSS/First_steps/How_CSS_is_structured +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/CSS/First_steps/Getting_started", "Learn/CSS/First_steps/How_CSS_works", "Learn/CSS/First_steps")}}
+ +

Agora que você tem uma ideia sobre o que é o CSS e seu uso basico, é hora de olhar um pouco mais a fundo das estruturas da linguagem em si. Nós ja conhecemos muitos conceitos discutidos aqui, entretanto, você pode voltar para qualquer um em específico, se achar algum dos proximos conceitos um tanto confuso

+ + + + + + + + + + + + +
Pré-requisitos:Conceitos básicos de computação, softwares básicos instalados, conhecimentos básicos de operação com arquivos,  básico de HTML (veja Introdução ao HTML), e  uma ideia de Como  funciona o CSS.
Objetivo:Aprender as estruturas da sintaxe básica do CSS em detalhes.
+ +

Aplicando CSS no seu HTML

+ +

A primeira coisa que você vai olhar é, os três métodos de aplicação do CSS em um documento.

+ +

Folha de Estilos Externa

+ +

Em Começando com o CSS nós linkamos uma folha de estilos externas em nossa página. Isso é o metodo mias comum utilizado para juntar CSS em um documento, podendo utilizar tal método em multiplas páginas, permitindo você estillizar todas as páginas como as mesmas folha de estilos. Na maioria dos casos, as diferentes páginas do site vão parecer bem iguais entre si e por isso você pode usar as mesmas regras para o estilo padrão da página.

+ +

Uma folha de estilos externa  é quando você tem seu CSS escrito em um arquivo separado com uma extensão .css, e você o refere dentro de um elemento <link> do HTML:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My CSS experiment</title>
+    <link rel="stylesheet" href="styles.css">
+  </head>
+  <body>
+    <h1>Hello World!</h1>
+    <p>This is my first CSS example</p>
+  </body>
+</html>
+ +

O arquivo CSS deve se parecer com algo nesse estilo:

+ +
h1 {
+  color: blue;
+  background-color: yellow;
+  border: 1px solid black;
+}
+
+p {
+  color: red;
+}
+ +

O atributo href do elemento {{htmlelement("link")}}, precisa fazer referência a um arquivo em nosso sistema de arquivos.

+ +

No exemplo abaixo, o arquivo CSS está na mesma pasta que o documento HTML, mas você pode colocá-lo em outro lugar e reajustar o caminho marcado para encontrá-lo, como a seguir: 

+ +
<!-- Inside a subdirectory called styles inside the current directory -->
+<link rel="stylesheet" href="styles/style.css">
+
+<!-- Inside a subdirectory called general, which is in a subdirectory called styles, inside the current directory -->
+<link rel="stylesheet" href="styles/general/style.css">
+
+<!-- Go up one directory level, then inside a subdirectory called styles -->
+<link rel="stylesheet" href="../styles/style.css">
+ +

Folha de estilos interna

+ +

Uma folha de estilos interna é  usada quando você não tem um arquivo CSS externo, mas, ao contrário,  coloca seu CSS dentro de elemento {{htmlelement("style")}} localizado no {{htmlelement("head")}} do documento HTML.

+ +

Deste modo, seu HTML se parecerá assim:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My CSS experiment</title>
+    <style>
+      h1 {
+        color: blue;
+        background-color: yellow;
+        border: 1px solid black;
+      }
+
+      p {
+        color: red;
+      }
+    </style>
+  </head>
+  <body>
+    <h1>Hello World!</h1>
+    <p>This is my first CSS example</p>
+  </body>
+</html>
+ +

Isso pode ser útil em algumas circunstâncias (talvez você esteja trabalhando em um sistema de gerenciamento de conteúdo - CMS - onde não tem permissão para modificar diretamente os arquivos CSS), entretanto isso não é tão eficiente quanto o uso de folhas de estilo externas — em um website, o CSS precisaria ser repetido em todas as páginas e atualizado em vários locais sempre que mudanças fossem necessárias.

+ +

Estilos inline

+ +

Estilos inline são declarações CSS que afetam apenas um determinado elemento, inserido em um atributo style:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My CSS experiment</title>
+  </head>
+  <body>
+    <h1 style="color: blue;background-color: yellow;border: 1px solid black;">Hello World!</h1>
+    <p style="color:red;">This is my first CSS example</p>
+  </body>
+</html>
+ +

Por favor, não utilize isso a menos que seja estritamente necessário! É péssimo para manutenção (você precisará atualizar a mesma informação diversas vezes em cada documento), além do que, mistura sua informação de estilização do CSS com sua informação de estrutura HTML, tornando seu código de difícil leitura e compreensão. Manter diferentes tipos de código separados torna o trabalho muito mais fácil para todos os que trabalham no código.

+ +

Existem alguns lugares onde o estilo embutido é mais comum, ou mesmo aconselhável. Você pode ter que recorrer ao uso deles se seu ambiente de trabalho for realmente restritivo (talvez o seu CMS permita apenas que você edite o corpo do HTML). Você também os verá sendo muito usados em e-mails em HTML de modo a obter compatibilidade com o maior número possível de clientes de e-mail.

+ +

Playing with the CSS in this article

+ +

There is a lot of CSS to play with in this article. To do so, we'd recommend creating a new directory/folder on your computer, and inside it creating a copy of the following two files:

+ +

index.html:

+ +
<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8">
+    <title>My CSS experiments</title>
+    <link rel="stylesheet" href="styles.css">
+  </head>
+  <body>
+
+    <p>Create your test HTML here</p>
+
+  </body>
+</html>
+ +

styles.css:

+ +
/* Create your test CSS here */
+
+p {
+  color: red;
+}
+ +

Then, when you come across some CSS you want to experiment with, replace the HTML <body> contents with some HTML to style, and start adding CSS to style it inside your CSS file.

+ +

If you are not using a system where you can easily create files, you can instead use the interactive editor below to experiment.

+ +

{{EmbedGHLiveSample("css-examples/learn/getting-started/experiment-sandbox.html", '100%', 800)}} 

+ +

Read on, and have fun!

+ +

Seletores

+ +

Não é possível falar de CSS sem conhecer os seletores, e nós já descobrimos vários tipos diferentes no tutorial Começando com o Css. Um seletor é o modo pelo qual nós apontamos para alguma coisa no nosso documento HTML para aplicar os estilos à ela. Se os seus estilos não forem aplicados, então é provável que o seu seletor não esteja ligado aquilo que você pensa que ele deveria.

+ +

Each CSS rule starts with a selector or a list of selectors in order to tell the browser which element or elements the rules should apply to. All of the following are examples of valid selectors, or lists of selectors.

+ +
h1
+a:link
+.manythings
+#onething
+*
+.box p
+.box p:first-child
+h1, h2, .intro
+ +

Try creating some CSS rules that use the above selectors, and some HTML to be styled by them. If you don't know what some of the above syntax means, try searching for it on MDN!

+ +
+

Note: You will learn a lot more about selectors in our CSS selectors tutorials, in the next module.

+
+ +

Specificity

+ +

There will often be scenarios where two selectors could select the same HTML element. Consider the stylesheet below where I have a rule with a p selector that will set paragraphs to blue, and also a class that will set selected elements red.

+ +
.special {
+  color: red;
+}
+
+p {
+  color: blue;
+}
+ +

Let's say that in our HTML document we have a paragraph with a class of special. Both rules could apply, so which one wins? What color do you think our paragraph will become?

+ +
<p class="special">What color am I?</p>
+ +

The CSS language has rules to control which rule will win in the event of a collision — these are called cascade and specificity. In the below code block we have defined two rules for the p selector, but the paragraph ends up being colored blue. This is because the declaration that sets it to blue appears later in the stylesheet, and later styles override earlier ones. This is the cascade in action.

+ +
p {
+  color: red;
+}
+
+p {
+  color: blue;
+}
+ +

However, in the case of our earlier block with the class selector and the element selector, the class will win, making the paragraph red — even thought it appears earlier in the stylesheet. A class is described as being more specific, or having more specificity than the element selector, so it wins.

+ +

Try the above experiment for yourself — add the HTML to your experiment, then add the two p { ... } rules to your stylesheet. Next, change the first p selector to .special to see how it changes the styling.

+ +

The rules of specificity and the cascade can seem a little complicated at first and are easier to understand once you have built up further CSS knowledge. In our Cascade and inheritance article, which you'll get to in the next module, I'll explain this in detail, including how to calculate specificity. For now, remember that this exists, and that sometimes CSS might not apply like you expect it to because something else in your stylesheet has a higher specificity. Identifying that more than one rule could apply to an element is the first step in fixing such issues.

+ +

Propriedades e valores

+ +

At its most basic level, CSS consists of two building blocks:

+ + + +

The below image highlights a single property and value. The property name is color, and the value blue.

+ +

A declaration highlighted in the CSS

+ +

A property paired with a value is called a CSS declaration. CSS declarations are put within CSS Declaration Blocks. This next image shows our CSS with the declaration block highlighted.

+ +

A highlighted declaration block

+ +

Finally, CSS declaration blocks are paired with selectors to produce CSS Rulesets (or CSS Rules). Our image contains two rules, one for the h1 selector and one for the p selector. The rule for h1 is highlighted.

+ +

The rule for h1 highlighted

+ +

Setting CSS properties to specific values is the core function of the CSS language. The CSS engine calculates which declarations apply to every single element of a page in order to appropriately lay it out and style it. What is important to remember is that both properties and values are case-sensitive in CSS. The property and value in each pair is separated by a colon (:).

+ +

Try looking up different values of the following properties, and writing CSS rules that apply them to different HTML elements:

+ + + +
+

Important: If a property is unknown or if a value is not valid for a given property, the declaration is deemed invalid and is completely ignored by the browser's CSS engine.

+
+ +
+

Important: In CSS (and other web standards), US spelling has been agreed on as the standard to stick to where language uncertainty arises. For example, color should always be spelled color. colour won't work.

+
+ +

Functions

+ +

While most values are relatively simple keywords or numeric values, there are some possible values which take the form of a function. An example would be the calc() function. This function allows you to do simple math from within your CSS, for example:

+ +
+
<div class="outer"><div class="box">The inner box is 90% - 30px.</div></div>
+ +
.outer {
+  border: 5px solid black;
+}
+
+.box {
+  padding: 10px;
+  width: calc(90% - 30px);
+  background-color: rebeccapurple;
+  color: white;
+}
+
+ +

This renders like so:

+ +

{{EmbedLiveSample('calc_example', '100%', 200)}}

+ +

A function consists of the function name, and then some brackets into which the allowed values for that function are placed. In the case of the calc() example above I am asking for the width of this box to be 90% of the containing block width, minus 30 pixels. This isn't something I can calculate ahead of time and just enter the value into the CSS, as I don't know what 90% will be. As with all values, the relevant page on MDN will have usage examples so you can see how the function works.

+ +

Another example would be the various values for {{cssxref("transform")}}, such as rotate().

+ +
+
<div class="box"></div>
+ +
.box {
+  margin: 30px;
+  width: 100px;
+  height: 100px;
+  background-color: rebeccapurple;
+  transform: rotate(0.8turn)
+}
+
+ +

The output from the above code looks like this:

+ +

{{EmbedLiveSample('transform_example', '100%', 200)}}

+ +

Try looking up different values of the following properties, and writing CSS rules that apply them to different HTML elements:

+ + + +

@rules

+ +

As yet, we have not encountered @rules (pronounced "at-rules"). These are special rules giving CSS some instruction on how to behave. Some @rules are simple with the rule name and a value. For example, to import an additional stylesheet into your main CSS stylesheet you can use @import:

+ +
@import 'styles2.css';
+ +

One of the most common @rules you will come across is @media, which allows you to use media queries to apply CSS only when certain conditions are true (e.g. when the screen resolution is above a certain amount, or the screen is wider than a certain width).

+ +

In the below CSS, we have a stylesheet that gives the <body> element a pink background color. However, we then use @media to create a section of our stylesheet that will only be applied in browsers with a viewport wider than 30em. If the browser is wider than 30em then the background color will be blue.

+ +
body {
+  background-color: pink;
+}
+
+@media (min-width: 30em) {
+  body {
+    background-color: blue;
+  }
+}
+ +

You will encounter other @rules throughout these tutorials.

+ +

See if you can add a media query to your CSS that changes styles based on the viewport width. Change the width of your browser window to see the result.

+ +

Shorthands

+ +

Some properties like {{cssxref("font")}}, {{cssxref("background")}}, {{cssxref("padding")}}, {{cssxref("border")}}, and {{cssxref("margin")}} are called shorthand properties — this is because they allow you to set several property values in a single line, saving time and making your code neater in the process.

+ +

For example, this line:

+ +
/* In 4-value shorthands like padding and margin, the values are applied
+   in the order top, right, bottom, left (clockwise from the top). There are also other
+   shorthand types, for example 2-value shorthands, which set padding/margin
+   for top/bottom, then left/right */
+padding: 10px 15px 15px 5px;
+ +

Does the same thing as all these together:

+ +
padding-top: 10px;
+padding-right: 15px;
+padding-bottom: 15px;
+padding-left: 5px;
+ +

Whereas this line:

+ +
background: red url(bg-graphic.png) 10px 10px repeat-x fixed;
+ +

Does the same thing as all these together:

+ +
background-color: red;
+background-image: url(bg-graphic.png);
+background-position: 10px 10px;
+background-repeat: repeat-x;
+background-scroll: fixed;
+ +

We won't attempt to teach these exhaustively now — you'll come across many examples later on in the course, and you are advised to look up the shorthand property names in our CSS reference to find out more.

+ +

Try adding the above declarations to your CSS to see how it affects the styling of your HTML. Try experimenting with some different values.

+ +
+

Warning: While shorthands often allow you to miss out values, they will then reset any values that you do not include to their initial values. This ensures that a sensible set of values are used. However, this might be confusing if you were expecting the shorthand to only change the values you passed in.

+
+ +

Comments

+ +

As with HTML, you are encouraged to make comments in your CSS, to help you understand how your code works when coming back to it after several months, and to help others coming to the code to work on it understand it.

+ +

Comments in CSS begin with /* and end with */. In the below code block I have used comments to mark the start of different distinct code sections. This is useful to help you navigate your codebase as it gets larger — you can search for the comments in your code editor.

+ +
/* Handle basic element styling */
+/* -------------------------------------------------------------------------------------------- */
+body {
+  font: 1em/150% Helvetica, Arial, sans-serif;
+  padding: 1em;
+  margin: 0 auto;
+  max-width: 33em;
+}
+
+@media (min-width: 70em) {
+  /* Let's special case the global font size. On large screen or window,
+     we increase the font size for better readability */
+  body {
+    font-size: 130%;
+  }
+}
+
+h1 {font-size: 1.5em;}
+
+/* Handle specific elements nested in the DOM  */
+/* -------------------------------------------------------------------------------------------- */
+div p, #id:first-line {
+  background-color: red;
+  background-style: none
+}
+
+div p{
+  margin: 0;
+  padding: 1em;
+}
+
+div p + p {
+  padding-top: 0;
+}
+ +

Comments are also useful for temporarily commenting out certain parts of the code for testing purposes, for example if you are trying to find which part of your code is causing an error. In the next example I have commented out the rules for the .special selector.

+ +
/*.special {
+  color: red;
+}*/
+
+p {
+  color: blue;
+}
+ +

Add some comments to your CSS, to get used to using them.

+ +

Whitespace

+ +

White space means actual spaces, tabs and new lines. In the same manner as HTML, the browser tends to ignore much of the whitespace inside your CSS; a lot of the whitespace is just there to aid readability.

+ +

In our first example below we have each declaration (and rule start/end) on its own line — this is arguably a good way to write CSS, as it makes it easy to maintain and understand:

+ +
body {
+  font: 1em/150% Helvetica, Arial, sans-serif;
+  padding: 1em;
+  margin: 0 auto;
+  max-width: 33em;
+}
+
+@media (min-width: 70em) {
+  body {
+    font-size: 130%;
+  }
+}
+
+h1 {
+  font-size: 1.5em;
+}
+
+div p,
+#id:first-line {
+  background-color: red;
+  background-style: none
+}
+
+div p {
+  margin: 0;
+  padding: 1em;
+}
+
+div p + p {
+  padding-top: 0;
+}
+
+ +

You could write exactly the same CSS like so, with most of the whitespace removed — this is functionally identical to the first example, but I'm sure you'll agree that it is somewhat harder to read:

+ +
body {font: 1em/150% Helvetica, Arial, sans-serif; padding: 1em; margin: 0 auto; max-width: 33em;}
+@media (min-width: 70em) { body {font-size: 130%;} }
+
+h1 {font-size: 1.5em;}
+
+div p, #id:first-line {background-color: red; background-style: none}
+div p {margin: 0; padding: 1em;}
+div p + p {padding-top: 0;}
+
+ +

The code layout you choose is usually a personal preference, although when you start to work in teams, you may find that the existing team has its own styleguide that specifies an agreed convention to follow.

+ +

The whitespace you do need to be careful of in CSS is the whitespace between the properties and their values. For example, the following declarations are valid CSS:

+ +
margin: 0 auto;
+padding-left: 10px;
+ +

But the following are invalid:

+ +
margin: 0auto;
+padding- left: 10px;
+ +

0auto is not recognised as a valid value for the margin property (0 and auto are two separate values,) and the browser does not recognise padding- as a valid property. So you should always make sure to separate distinct values from one another by at least a space, but keep property names and property values together as single unbroken strings.

+ +

Try playing with whitespace inside your CSS, to see what breaks things and what doesn't.

+ +

What's next?

+ +

It's useful to understand a little about how the browser takes your HTML and CSS and turns it into a webpage, so in the next article — How CSS works — we will take a look at that process.

+ +

{{PreviousMenuNext("Learn/CSS/First_steps/Getting_started", "Learn/CSS/First_steps/How_CSS_works", "Learn/CSS/First_steps")}}

+ +

Neste módulo

+ +
    +
  1. O que é CSS?
  2. +
  3. Começando com CSS
  4. +
  5. Como o CSS é  estruturado
  6. +
  7. Como o CSS funciona
  8. +
  9. Usando seu novo conhecimento
  10. +
diff --git a/files/pt-br/learn/css/first_steps/how_css_works/index.html b/files/pt-br/learn/css/first_steps/how_css_works/index.html new file mode 100644 index 0000000000..55bc0f1978 --- /dev/null +++ b/files/pt-br/learn/css/first_steps/how_css_works/index.html @@ -0,0 +1,161 @@ +--- +title: Como funciona o CSS +slug: Learn/CSS/First_steps/How_CSS_works +tags: + - CSS + - DOM + - Iniciante + - aprenda +translation_of: Learn/CSS/First_steps/How_CSS_works +--- +

{{LearnSidebar}}
+ {{PreviousMenuNext("Learn/CSS/First_steps/How_CSS_is_structured", "Learn/CSS/First_steps/Using_your_new_knowledge", "Learn/CSS/First_steps")}}

+ +

Nós aprendemos o básico de CSS, porque e como escrever simples folhas de estílo. Nesta lição, nós daremos uma olhada em como um navegador transforma um CSS e HTML em uma página da web.

+ + + + + + + + + + + + +
Pré-requisito:Alfabetização em computação básica, softwares básicos instalados, conhecimento básico sobre trabalhar com arquivos, e o básico de HTML (estude Introdução ao HTML.)
Objetivo:Entender o básico sobre como o CSS e o HTML são interpretados pelo navegador (que em seu nome original chama-se browser do inglês), e o que acontece quando um browser encontra regras CSS mas não as compreende.
+ +

Como o CSS funciona?

+ +

Quando um navegador redenriza um documento, ele combina o documento com suas informações de estilo. E o documento é processado em estágios, nos quais estão listados abaixo. É sugerível ter em mente que esta é uma versão simplificada do que ocorre quando um navegador redenriza uma página web, e que diferentes navegadores podem manipular estes processos de diferentes formas. De toda forma, esta listagem é muito aproximada do processo comum feito pela maioria dos navegadores.

+ +
    +
  1. O navegador carrega o HTML (e.g. que é recebido pela internet).
  2. +
  3. Ele então converte o {{Glossary("HTML")}} para um {{Glossary("DOM")}} (Document Object Model). O DOM representa o documento na memória do computador. O DOM será também melhor detalhado na próxima seção.
  4. +
  5. O navegador então requisita a maioria dos recursos que estão lincados no documento HTML, elementos como imagens encorporadas e vídeos, e também, folhas de estilo CSS. O código em JavaScript é manipulado um pouco mais tarde durante o processo, e não falaremos muito sobre a manipulação do JavaScript agora para mantermos as coisas simples.
  6. +
  7. O navegador analisa o CSS encontrado (fetched) e interpreta as diferentes regras por meio de seus diferentes tipos de seletores em diferentes baldes (buckets), tais como elementos (ex: h1, h2), classes (.myElement), ID (#myNav), e outros mais. Baseado nos seletores encontrados, o navegador insere as regras de estilização que devem ser aplicadas para cada node no DOM, e anexa o estilo para os elementos como foram especificados nas folhas de estilização (este processo intermediário é chamado de render tree ou árvore de renderização).
  8. +
  9. A árvore de renderização é organizada na estrutura e deve aparecer depois das regras de estilo serem aplicadas ao documento.
  10. +
  11. O visual de visualização da página é por fim mostrado na tela (este estágio é chamado de painting ou pintura).
  12. +
+ +

O diagrama a seguir também apresenta uma visão simples do processo.

+ +

+ +

Sobre o DOM

+ +

Um DOM uma estrutura árborea (tree-like). Cada elemento, atributo, ou fragmento de texto na linguagem de marcação (markup language) torna-se um {{Glossary("Node/DOM","DOM node (nó ou ponto de intersecção)")}} na estrutura de árvore. Os nodes (nós) são definidos por meio do relacionamento com outros nodes presentes DOM. Alguns elementos são pais ou superiores a elementos dentro de si (child node, ou em português, nós filhos ou nós secundários), e child nodes possuem elementos irmãos.

+ +

Compreender o DOM ajuda você organizar, debugar e manter seu CSS porque o DOM é onde seu CSS e o conteúdo do documento são combinados. Quando você começa a trabalhar com as DevTools do browser você estará navegando os elementos do DOM como itens ordenados selecionáveis para assim decidir quais regras de estilização aplicar.

+ +

Uma representação prática do DOM

+ +

Ao invés de um longa e chata explicação, vamos observar um exemplo para vermos como um trecho real de um documento HTML é convertido em um DOM.

+ +

Pegue o seguinte código HTML:

+ +
<p>
+  Let's use:
+  <span>Cascading</span>
+  <span>Style</span>
+  <span>Sheets</span>
+</p>
+
+ +

No DOM, o node (nó) especifica nosso elementro <p> como um elemento pai. Seus filhos são um text node e a árvore de nós que corresponde ao nossos elementos <span>. Os nós SPAN são também elementos pais, tendo os text nodes (textos dentro de si) como seus filhos:

+ +
P
+├─ "Let's use:"
+├─ SPAN
+|  └─ "Cascading"
+├─ SPAN
+|  └─ "Style"
+└─ SPAN
+   └─ "Sheets"
+
+ +

Esta é a forma como um browser interpreta o nosso trecho de documento HTML acima apresentado — O browser renderiza a árvore DOM e nos retorna uma saída no browser da seguinte forma:

+ +

{{EmbedLiveSample('A_real_DOM_representation', '100%', 55)}}

+ + + +

Aplicando CSS ao DOM

+ +

Vamos adicionar um curto CSS ao nosso documento, para estiliza-lo. Novamente, usamos o trecho HTML seguinte:

+ +
<p>
+  Let's use:
+  <span>Cascading</span>
+  <span>Style</span>
+  <span>Sheets</span>
+</p>
+ +

Vamos supor que aplicamos o seguinte CSS a ele:

+ +
span {
+  border: 1px solid black;
+  background-color: lime;
+}
+ +

O browser irá interpretar o HTML e criar um DOM baseado nele. Como a única regra de estilização CSS disponível possui um seletor span, o browser fará a combinação do CSS rapidamente! Ele irá aplicar a regra de estilo para cada um da árvore <span>s, e então paint (pintar) o resultado final na tela.

+ +

Ao atualizar há a seguinte saída:

+ +

{{EmbedLiveSample('Applying_CSS_to_the_DOM', '100%', 55)}}

+ +

Em nosso artigo Debugging CSS no próximo módulo nós estaremos usando as DevTools do browser para debugar problemas no CSS, e aprenderemos mais sobre como o navegador interpreta o CSS.

+ +

O que acontece se um navegador não entende o CSS encontrado?

+ +

Em uma lição anterior, eu mencionei que navegadores não implementam todo o novo CSS ao mesmo tempo. Em adição, muitas pessoas não usam a versão mais recente de um navegador. Dado que o CSS é processado o tempo todo, e que portanto está adiantado em relação ao que os browsers podem reconhecer, você pode imaginar o que acontece se um browser encontra um seletor ou uma declaração CSS que ele não reconhece.

+ +

A resposta é que ele não faz nada e vai para o próximo conteúdo em CSS!

+ +

Se um browser está analisando suas regras, e econtra uma porpriedade ou valor que ele não entende, ele o ignora e segue para a próxima declaração. Ele vai fazer isto se você cometeu algum erro ou digitou incorretamente uma propriedade ou valor, ou se tal propriedade ou valor é recente e o browser ainda não o processa.

+ +

Similarmente, se um browser encontra um seletor que não comprrende, ele o ignorará e seguirá para a próxima regra.

+ +

No exemplo abaixo usei a grafia em inglês britânico para a propriedade cor, o que a torna inválida e portanto ela não é reconhecida. Por isso, o parágrafo não recebe a coloração azul. Todos os outros CSS foram aplicados, no entanto, apenas aquele que foi considerado inválido foi ignorado.

+ +
+
<p> Quero que este texto esteja grande, em negrito, e azul.</p>
+ +
p {
+  font-weight: bold;
+  colour: blue; /* grafia incorreta da propriedade cor */
+  font-size: 200%;
+}
+
+ +

{{EmbedLiveSample('Skipping_example', '100%', 200)}}

+ +

Este comportamento é bastante útil. Ele significa qeu você pode usar o novo CSS como uma melhoria, sabendo que não ocorrerá um erro se ele não for completamente compreendido - o browser  ou vai entender esta característica ou não. Em conjunto com a maneira que  a cascata funciona, e o fato que browsers usarão o último CSS que eles encontrarem numa folha de estilos quando você possui duas regras com a mesma especificidade, Você pode oferecer alternativas para browsers  que não processa CSS mais novos.

+ +

Isto funciona particularmente bem quando você usa um valor que é relativamente recente e que não é processado em todo lugar. Por exemplo, alguns browsers antigos não processam calc() como um valor. Eu posso dar um recuo com uma largura em pixels para um box, e então seguir e dar uma largura com o valor de 100% - 50px com calc(). Browsers antigos irão utilizar a versão em pixels, ignorando a linha que trata de calc(), já que eles não a compreendem. Browsers mais novos irão interpretar inicialmente a linha que utiliza pixels, para em seguida a sobrepor com a linha utilizando calc() conforme ela aparece na cascata.

+ +
.box {
+  width: 500px;
+  width: calc(100% - 50px);
+}
+ +

Iremos visualizar várias outras maneiras de auxiliar diferentes browsers em lições futuras.

+ +

E por último

+ +

Você está quase encerrando este módulo; só temos mais uma tarefa para fazer. No próximo artigo, você utilizará seu novo conhecimento para reestilizar um exemplo, testando seus aprendizados de CSS no processo.

+ +

{{PreviousMenuNext("Learn/CSS/First_steps/How_CSS_is_structured", "Learn/CSS/First_steps/Using_your_new_knowledge", "Learn/CSS/First_steps")}}

+ +

Neste módulo

+ +
    +
  1. O que é CSS?
  2. +
  3. Começando com CSS
  4. +
  5. Como o CSS é estruturado
  6. +
  7. Como o CSS funciona
  8. +
  9. Utilizando seu novo conhecimento
  10. +
diff --git a/files/pt-br/learn/css/first_steps/index.html b/files/pt-br/learn/css/first_steps/index.html new file mode 100644 index 0000000000..a15ff4c7b3 --- /dev/null +++ b/files/pt-br/learn/css/first_steps/index.html @@ -0,0 +1,56 @@ +--- +title: Primeiros passos com CSS +slug: Learn/CSS/First_steps +tags: + - Beginner + - CSS + - Iniciante + - Landing + - Learn + - Module + - Primeiros passos + - aprenda + - first steps +translation_of: Learn/CSS/First_steps +--- +
{{LearnSidebar}}
+ +

CSS ( Planilhas de estilo em cascata) é usada para estilizar e arranjar páginas web — por exemplo, para alterar a fonte, cor, tamanho e espaçamento do seu conteúdo, separá-lo em multiplas colunas, ou então adicionar animações e outras implementações decorativas. Esse módulo provê um começo sutil em seu caminho pelo domínio do CSS com o básico de como ele funciona, como é a aprência da sintaxe e como você pode começar a utilizá-lo para estilizar seu HTML.

+ +

Pré-requisitos

+ +

Antes de iniciar este módulo, você deve ter:

+ +
    +
  1. Familiaridade básica com o uso de computadores e utilização da internet passivamente (Ex: vendo e consumindo o conteúdo.)
  2. +
  3. Um ambiente de trabalho básico configurado conforme detalhado em Instalando Software Básico e um entendimento de como criar e gerenciar arquivos, conforme detalhado em Lidando com Arquivos.
  4. +
  5. Familiaridade básica com HTML, como discutido no módulo Introdução ao HTML.
  6. +
+ +
+

Nota: Se você está trabalhando em um computador/tablet/ou outro dispostivo onde você não tem habilidade para criar seus próprios arquivos, você poderá tentar (a maioria) os exemplos de códigos em um programa online de codificação como JSBin ou Thimble.

+
+ +

Guias

+ +

Este módulo contém os seguintes artigos, que o guiarão através de toda a teoria básica do CSS e fornecerão oportunidades para você testar algumas habilidades.

+ +
+
O que é CSS?
+
{{Glossary("CSS")}} (Cascading Style Sheets) permite que você crie páginas web com ótima aparência. Mas como isso funciona por debaixo dos panos? Este artigo explica o que é CSS, com um exemplo simples de sintaxe, e também cobre alguns termos importantes sobre a linguagem.
+
Iniciando com CSS
+
Neste artigo, pegaremos um documento HTML simples e aplicaremos CSS, aprendendo algumas coisas práticas sobre a linguagem ao longo do caminho.
+
Como CSS é estruturado
+
Agora que você tem uma idéia sobre o que é CSS e o básico sobre como usá-lo, é hora de analisar um pouco mais a fundo a estrutura da própria linguagem. Já conhecemos muitos dos conceitos discutidos aqui; você pode retornar a este para recapitular se achar confusos os conceitos posteriores.
+
Como CSS funciona
+
Aprendemos o básico do CSS, para que serve e como escrever folhas de estilo simples(Cascading Style Sheets - CSS). Neste exercício, veremos como um navegador utiliza CSS e HTML, e os transforma em uma página da web.
+
Usando seu novo conhecimento
+
Com o que aprendeu nas poucas lições anteriores, você já deve estar achando que pode formatar simples documentos de textos usando CSS, para adicionar seu próprio estilo neles. Este artigo te dará a chance de fazê-lo.
+
+ +

Veja também

+ +
+
Conhecimento Intermerdiário da Web 1: Introdução ao CSS
+
Um excelente curso básico da Mozilla que explora e testa muitas das habilidades mencionadas no módulo Introdução ao CSS. Aprenda sobre o estilo de elementos HTML em uma página web, seletores de CSS, atributos e valores.
+
diff --git a/files/pt-br/learn/css/first_steps/iniciando/index.html b/files/pt-br/learn/css/first_steps/iniciando/index.html new file mode 100644 index 0000000000..a9a5218e98 --- /dev/null +++ b/files/pt-br/learn/css/first_steps/iniciando/index.html @@ -0,0 +1,265 @@ +--- +title: Iniciando com CSS +slug: Learn/CSS/First_steps/Iniciando +tags: + - Aprender + - CSS + - Classes + - Elementos + - Estado + - Iniciante + - Seletores + - Sintaxe +translation_of: Learn/CSS/First_steps/Getting_started +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/CSS/First_steps/What_is_CSS", "Learn/CSS/First_steps/How_CSS_is_structured", "Learn/CSS/First_steps")}}
+ +

Neste artigo iremos pegar um simples documento HTML e aplicar o CSS nele, aprendendo algumas coisas práticas sobre a linguagem no decorrer do processo.

+ + + + + + + + + + + + +
pré-requisitos: +

Conhecimento básico sobre computador, softwares básicos instalados, conhecimento básico de como trabalhar com arquivos, e conhecimento básico sobre HTML (estude Introdução ao HTML.)

+
Objetivo:Entender os fundamentos que vinculam um documento CSS a um arquivo HTML, e ser capaz de estilizar um texto simples com CSS.
+ +

Iniciando com algum HTML

+ +

Nosso ponto de partida e um documento HTML. Você pode copiar o código abaixo se desejar trabalhar no seu próprio computador. Salve-o como index.html em uma pasta, no seu computador.

+ +
<!doctype html>
+<html lang="en">
+<head>
+    <meta charset="utf-8">
+    <title>Getting started with CSS</title>
+</head>
+
+<body>
+
+    <h1>I am a level one heading</h1>
+
+    <p>This is a paragraph of text. In the text is a <span>span element</span>
+and also a <a href="http://example.com">link</a>.</p>
+
+    <p>This is the second paragraph. It contains an <em>emphasized</em> element.</p>
+
+    <ul>
+        <li>Item one</li>
+        <li>Item two</li>
+        <li>Item <em>three</em></li>
+    </ul>
+
+</body>
+
+</html>
+
+ +
+

Observação: Se você está lendo isso em um dispositivo móvel ou em um ambiente onde não possa criar arquivos, não se preocupe — editores de código ao vivo estão disponíveis abaixo para permitir que você escreva o código de exemplo aqui, nesta página.

+
+ +

Adicionando CSS para o nosso documento

+ +

A primeira coisa que precisamos fazer é falar para o HTML que temos algumas regras CSS que desejamos usar. Há três formas diferentes de aplicar CSS a um documento HTML que você normalmente vai encontrar, contudo, por enquanto, iremos olhar para o mais habitual e útil – vincular o CSS a partir do cabeçalho do seu documento.

+ +

Crie um arquivo na mesma pasta em que se encontra o seu documento HTML e salve-o como style.css. A extensão .css nos informa que se trata de um arquivo CSS.

+ +

Para ligar o style.css ao index.html adicione a seguinte linha em algum lugar dentro do {{htmlelement("head")}} do documento HTML:

+ +
<link rel="stylesheet" href="styles.css">
+ +

Este {{htmlelement("link")}} elemento diz ao navegador que temos uma folha de estilo, usando o atributo rel, e a localização desse arquivo como o valor do atributo href. Você pode testar se esse CSS funciona adicionando regras ao styles.css. Usando o seu editor de código, adicione as linhas seguintes ao seu arquivo CSS:

+ +
h1 {
+  color: red;
+}
+ +

Salve os seus arquivos HTML e CSS e atualize a página no seu navegador. O nível de cabeçalho um, no topo do documento, deve estar agora em vermelho. Se tudo estiver correto, parabéns! - Você teve sucesso ao aplicar CSS a um documento HTML. Se nada aconteceu, observe cuidadosamente se você digitou tudo certo.

+ +

Você pode continuar trabalhando no styles.css localmente, ou pode usar nosso editor interativo abaixo pra continuar com este tutorial. O editor interativo age como se o CSS no primeiro painel estivesse vinculado ao documento HTML, assim como fizemos com o documento acima.

+ +

Estilizando elementos HTML

+ +

Fazendo o nosso cabeçalho ficar vermelho, demonstramos que podemos pegar e estilizar um elemento HTML. Fazemos isso especificando um seletor de elemento — Isto é, um seletor que combina diretamente com o nome do elemento HTML. Para especificar todos os parágrafos no documento, você usaria o seletor p. Para tornar todos os parágragos verdes, você usaria:

+ +
p {
+  color: green;
+}
+ +

Você pode especificar múltiplos seletores, separando-os com virgula. Se eu quero que todos os parágrafos e todos os itens da lista se tornem verdes, então minha regra se parecerá com isto:

+ +
p, li {
+    color: green;
+}
+ +

Experimente isso no editor interativo abaixo (edit the code boxes), ou no seu arquivo CSS local.

+ +

{{EmbedGHLiveSample("css-examples/learn/getting-started/started1.html", '100%', 900)}} 

+ +

Alterando o comportamento padrão dos elementos

+ +

Quando olhamos para um documento HTML bem marcado, até algo tão simples como o nosso exemplo, podemos ver como o navegador está tornando o HTML legível adicionando algum estilo padrão. Títulos são grandes e em negritos, nossa lista possui marcadores. Isso acontece porque navegadores tem uma folha de estilo interna contendo estilo padrão, a qual eles aplicam para toda a página por padrão; sem eles, todo o texto seria executado em conjunto e teríamos que estilizar tudo do princípio. Todos os modernos navegadores mostram conteúdo HTML por padrão, da mesma maneira.

+ +

Contudo, você frequentemente irá desejar algo diferente do que foi escolhido pelo navegador. Isso pode ser feito simplesmente escolhendo o elemento HTML que você quer mudar, e usando uma regra CSS para alterar a forma como ele se parece. Um bom exemplo é o nosso <ul>, uma lista não ordenada. Ele tem uma lista marcada, e, se decido não escolher essa marcação, posso removê-los fazendo assim:

+ +
li {
+  list-style-type: none;
+}
+ +

Experimente adicionar isto ao seu CSS agora.

+ +

A propriedade list-style-type é uma boa propriedade para se ver no MDN para ver quais valores são suportados. Dê uma olhada na página para list-style-type e encontrará um exemplo interativo no topo da página para experimentar alguns valores diferentes nele, todos os valores permitidos são detalhados mais abaixo na página.

+ +

Olhando para essa página você descobrirá que, além de remover a marcação da lista, que você também pode alterá-los — Teste mudá-los para marcação quadrada, usando valores de square.

+ +

Incluindo uma classe

+ +

Até agora, temos estilizado elementos baseado em seus nomes HTML. isto funciona enquanto você desejar que todos os elementos desse tipo, no seu documento, se pareçam o mesmo. Na maioria das vezes, isso não é o caso, e, então, você precisará encontrar uma maneira de selecionar um subconjunto de elementos sem alterar os outros. A maneira mais comum de fazer isso é adicionar uma classe ao seu elemento HTML e especificar essa classe.

+ +

No seu documento HTML, adicione um atributo de classe ao segundo item da lista. Sua lista se parecerá, agora, assim:

+ +
<ul>
+  <li>Item one</li>
+  <li class="special">Item two</li>
+  <li>Item <em>three</em></li>
+</ul>
+ +

No seu CSS, você pode especificar a classe special criando um seletor que inicia com um caractere de ponto final. Adicione o seguinte código ao seu arquivo CSS:

+ +
.special {
+  color: orange;
+  font-weight: bold;
+}
+ +

Salve e recarregue a página no navegador, para visualizar o resultado.

+ +

Você pode aplicar a classe special para qualquer elemento na sua página que desejar ter a mesma aparência o item dessa lista. Por exemplo, pode-se querer que o <span>, no parágrafo, também se torne laranja e em negrito. Experimente adicionar uma class de special a ele, em seguida, recarregue a sua página e veja o que acontece.

+ +

Algumas vezes, verá regras com um seletor que lista o seletor do elemento HTML junto com uma classe:

+ +
li.special {
+  color: orange;
+  font-weight: bold;
+}
+ +

Essa sintaxe significa "pegue qualquer elementoli que tenha uma classe special". Se você fizesse isso, não seria mais possível aplicar a classe a um <span> ou outro elemento, simplesmente adicionando a classe a ele; você teria que adicionar esse elemento à lista de seletores, assim:

+ +
li.special,
+span.special {
+  color: orange;
+  font-weight: bold;
+}
+ +

Como pode imaginar, algumas classes podem ser aplicadas a muitos elementos e você não quer ter que editar seu CSS a cada vez que algo novo precisar assumir esse estilo. Portanto, as vezes é melhor ignorar o lemento e simplesmente se referir à classe, a menos que você queira criar algumas regras especiais para um elemento em particular, e, talvez, queira ter certeza que eles não serão aplicados aos outros.

+ +

Estilizando coisas baseadas em sua localização no documento

+ +

Há momentos quando você desejará que algo se pareça diferente, baseado onde ele está no documento. Existem vários seletores que podem lhe ajudar aqui, mas, por enquanto, iremos olhar apenas alguns. No nosso documento estão dois elementos <em> — um dentro de um parágrafo e o outro dentro do item de lista. Para selecionar apenas um <em> aninhado dentro de um elemento <li> posso usar um seletor chamado combinador descendente, a qual simplesmente, assume a forma de um espaço entre dois outros seletores.

+ +

Adicione a seguinte regra a sua folha de estilo.

+ +
li em {
+  color: rebeccapurple;
+}
+ +

Este seletor selecionará qualquer elemento <em> que está dentro (um descendente de) um <li>. Deste modo, no seu documento de exemplo, você deve achar que o <em> no terceiro item da lista agora está roxo, mas o que está dentro do parágrafo permanece inalterado.

+ +

Outra coisa que você pode gostar de experimentar é estilizar um parágrafo quando ele vem diretamente após um título no mesmo nível de hierarquia no HTML. Para isso, coloque um +  (um combinador irmão adjacente) entre os seletores.

+ +

Experimente adicionar esta regra à sua folha de estilo também:

+ +
h1 + p {
+  font-size: 200%;
+}
+ +

O exemplo ativo abaixo inclui as duas regras acima. Verifique adicionando uma regra para tornar um span vermelho, se ele está dentro de um parágrafo. Você saberá se fez certo quando o span no primeiro parágrafo ficar vermelho, mas o do primeiro item da lista não mudar de cor.

+ +

{{EmbedGHLiveSample("css-examples/learn/getting-started/started2.html", '100%', 1100)}}

+ +
+

Observação: Como pode ver, CSS nos dá várias maneiras de especificar elementos, e temos somente arranhado a superfície até agora! Analisaremos adequadamente todos esses seletores e muitos outros, nos nossos artigos Seletores posteriormente neste curso.

+
+ +

Estilizando coisas baseadas no estado

+ +

O tipo final de estilo, que vamos dar uma olhada neste tutorial, é a habilidade de estilizar coisas com base em seu estado. Um exemplo direto disso é quando estilizamos links. Quando aplicamos um estilo a um link, precisamos especificar o elemento <a> (âncora). Isto possui diferentes estados, dependendo se ele foi visitado, se não foi visitado, se o mouse está passando por ele, se foi teclado ou no processo de ser clicado (ativado). Você pode usar CSS para especificar estes diferentes estados — o CSS abaixo estiliza links não visitados com a cor rosa e links visitados com a cor verde.

+ +
a:link {
+  color: pink;
+}
+
+a:visited {
+  color: green;
+}
+ +

Você pode alterar a aparência do link quando o usuário passa o mouse sobre ele. Por exemplo, removendo o sublinhado, o que é realizado na próxima regra:

+ +
a:hover {
+  text-decoration: none;
+}
+ +

No exemplo ativo abaixo, você pode brincar com diferentes valores para os vários estados do link. Adicionei as regras acima, e agora perceba que a cor rosa é bastante clara e difícil de ler. — porque não mudar isso para uma cor melhor? Pode deixá-los em negrito?

+ +

{{EmbedGHLiveSample("css-examples/learn/getting-started/started3.html", '100%', 900)}} 

+ +

Removemos o sublinhado do nosso link ao passar o mouse. Pode-se remover os sublinhados de todos os estados de um link. Vale lembrar, no entanto, que em um site real, você deseja garantir que os visitantes saibam que um link é um link. Deixar o sublinhado no lugar pode ser uma pista importante para as pessoas perceberem que é possível clicar em algum texto dentro de um parágrafo — esse é o comportamento ao qual estão acostumados. Como tudo em CSS, existe o potencial de tornar o documento menos acessível com suas alterações — procuraremos destacar possíveis armadilhas em locais apropriados.

+ +
+

Observação: Você verá frequentemente menção de acessibilidade nessas lições e no MDN. Quando falamos sobre acessibilidade, estamos nos referindo aos requerimentos para a nossa página web ser compreensível e utilizável por todos.

+ +

Seu visitante pode muito bem estar em um computador com um mouse defeituoso, ou um dispositivo móvel com uma tela sensível ao toque. Ou eles podem estar usando um leitor de tela, que lê o conteúdo do documento, ou podem precisar de muito texto grande, ou estar navegando no site apenas usando o teclado.

+ +

Um documento HTML simples é geralmente acessível a todos — Ao começar a estilizar esse documento, é importante que você não o rone menos acessível.

+
+ +

Combinando seletores e combinadores

+ +

Vale ressaltar que você pode combinar vários seletores e combinadores. Até agora, vimos assim:

+ +
/* selects any <span> that is inside a <p>, which is inside an <article>  */
+article p span { ... }
+
+/* selects any <p> that comes directly after a <ul>, which comes directly after an <h1>  */
+h1 + ul + p { ... }
+ +

Você pode combinar multiplos tipos juntos, também. Experimente acrescentar o seguinte código:

+ +
body h1 + p .special {
+  color: yellow;
+  background-color: black;
+  padding: 5px;
+}
+ +

Isso estilizará qualquer elemento com a classe special, a qual está dentro de um <p>, que vem logo após um <h1>, que, por sua vez, está dentro de um <body>. Ufa!

+ +

No HTML original que forncemos, o único elemento estilizado é <span class="special">.

+ +

Não se preocupe se isto parece complicado no momento — em breve, você começará a entender como escreve mais CSS.

+ +

Empacotando

+ +

Neste tutorial, demos uma olhada na quantidade de maneiras as quais pode-se estilizar um documento usando CSS. Estaremos desenvolvendo esse conhecimento ao longo da caminhada através das Lições. No entanto, agora, você já sabe o suficiente para estilizar o texto, aplicar CSS com base em diferentes maneiras de especificar elementos no documento e procurar propriedades e valores na documentação do MDN.

+ +

Na próxima lição, veremos como o CSS é estruturado.

+ +

{{PreviousMenuNext("Learn/CSS/First_steps/What_is_CSS", "Learn/CSS/First_steps/How_CSS_is_structured", "Learn/CSS/First_steps")}}

+ +

Neste módulo

+ +
    +
  1. O que é CSS?
  2. +
  3. Começando com CSS
  4. +
  5. Como o CSS é estruturado
  6. +
  7. Como o CSS funciona
  8. +
  9. Usando o seu novo conhecimento
  10. +
diff --git a/files/pt-br/learn/css/first_steps/o_que_e_css/index.html b/files/pt-br/learn/css/first_steps/o_que_e_css/index.html new file mode 100644 index 0000000000..41980dfee6 --- /dev/null +++ b/files/pt-br/learn/css/first_steps/o_que_e_css/index.html @@ -0,0 +1,127 @@ +--- +title: O que é CSS? +slug: Learn/CSS/First_steps/O_que_e_CSS +tags: + - Aprender + - CSS + - Iniciante + - Introdução ao CSS + - Módulos + - Sintaxe + - especificação +translation_of: Learn/CSS/First_steps/What_is_CSS +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/CSS/First_steps/Getting_started", "Learn/CSS/First_steps")}}
+ +

{{Glossary("CSS")}} (Folhas de Estilo em Cascata) permite a você criar páginas web agradáveis, mas como isso funciona por baixo dos panos? Este artigo explica o que é CSS, com um exemplo de sintaxe simples, e, também, trata alguns conceitos-chaves sobre a linguagem.

+ + + + + + + + + + + + +
Pré-requisitos:Conhecimento básico sobre computador, softwares básicos instalados, conhecimento básico de como trabalhar com arquivos, e conhecimento básico sobre HTML (estude Introdução ao HTML.)
Objetivo:Aprender o que é CSS.
+ +

No módulo Introdução ao HTML vimos o que é HTML, e como ele é usado para fazer marcação de documentos. Estes documentos serão legíveis em um navegador web. Títulos serão mais largos do que textos comuns, parágrafos quebram em uma nova linha e tendo espaços entre eles. Links são coloridos e sublinhados para distingui-los do resto do texto. O que você está vendo é o estilo padrão do navegador - vários estilos básicos que o navegador aplica ao HTML, para garantir que ele será legível mesmo se não for explicitamente estilizado pelo autor da página web.

+ +

The default styles used by a browser

+ +

No entanto, a web seria um lugar chato se todos os web sites tivessem estilos iguais ao mostrado na imagem acima. Usando CSS você pode controlar exatamente a aparência dos elementos HTML no navegador, apresentando a sua marcação com o design que desejar.

+ +

Para que serve o CSS?

+ +

Como falamos antes, CSS é uma linguagem para especificar como documentos são apresentados aos usuários — como eles são estilizados, dispostos etc.

+ +

Um documento é normalmente um arquivo texto estruturado usando uma linguagem de marcação — {{Glossary("HTML")}} é a linguagem de marcação mais comum, mas você também pode encontrar outras, como {{Glossary("SVG")}} ou {{Glossary("XML")}}.

+ +

Apresentar um documento para um usuário significa convertê-lo para um formato utilizável pelo seu público. {{Glossary("browser","Browsers")}}, como {{Glossary("Mozilla Firefox","Firefox")}}, {{Glossary("Google Chrome","Chrome")}}, ou {{Glossary("Microsoft Edge","Edge")}} , são projetados para apresentar documentos visualmente, por exemplo, um uma tela de computador, projetor ou impressora.

+ +
+

Observação: Um navegador web é as vezes chamado de {{Glossary("User agent","user agent")}}, o que, basicamente, significa um programa de computador que representa uma pessoa por trás do sistema. Navegadores web são o principal tipo de agente do usuário que nos referimos quando falamos sobre CSS, contudo, ele não é o único. Há outros agentes de usuário disponíveis — tais como aqueles que convertem documentos HTML e CSS para PDF a serem impressos.

+
+ +

O CSS pode ser usado para estilizar um documento muito básico de texto — por exemplo, alterando a cor e tamanho dos títulos e links. Pode ser usado para criar layout — por exemplo, transformando uma simples coluna de texto em um layout com uma área de conteúdo principal e um sidebar (barra lateral) para as informações relacionadas. Pode até ser usado para efeitos tais como animação. Dê uma olhada nos links deste parágrafo, para ver exemplos específicos.

+ +

Sintaxe CSS

+ +

CSS é uma linguagem baseada em regras. — Você define regras especificando grupos de estilo que devem ser aplicados para elementos particulares ou grupos de elementos na sua página web. Por exemplo, "Quero que o título principal, na minha página, seja mostrado como um texto grande e de cor vermelha.".

+ +

O código seguinte mostra uma regra CSS muito simples, que chegaria perto do estilo descrito acima:

+ +
h1 {
+    color: red;
+    font-size: 5em;
+}
+ +

A regra é aberta com um {{Glossary("CSS Selector", "selector")}} . Isso seleciona o elemento HTML que vamos estilizar. Neste caso, estamos estilizando títulos de nível um ({{htmlelement("h1")}}).

+ +

Temos, então, um conjunto de chaves { }. Dentro deles, haverá uma ou mais declarações, que tomam a forma de pares propriedade e valor. Cada par especifica uma propriedade do(s) elemento(s) que estamos selecionando e, em seguida, então um valor que gostaríamos de atribuir à propriedade

+ +

Antes dos dois pontos, temos a propriedade, e, depois, o valor. CSS {{Glossary("property/CSS","properties")}} possui diferentes valores permitidos, dependendo de qual propriedade está sendo especificado. Em nosso exemplo, temos a propriedade color, que pode tomar vários valores para cor. Também temos a propriedade font-size. Essa propriedade pode ter vários unidades de tamanho como um valor.

+ +

Uma folha de estilo CSS conterá muitas regras tais como essa, escrita uma após a outra.

+ +
h1 {
+    color: red;
+    font-size: 5em;
+}
+
+p {
+    color: black;
+}
+ +

Você constatará que rapidamente aprende alguns valores, enquanto outros precisará pesquisar. As páginas de propriedades individuais no MDN dá a você uma maneira rápida de procurar propriedades e seus respectivos valores, quando você esquecer, ou desejar saber quais valores pode usar.

+ +
+

Observação: Você pode achar links para todas as páginas de propriedades CSS (junto com outros recursos CSS) listados no MDN referência CSS. Alternativamente, você deve se acostumar a pesquisar por "mdn css-feature-name" no seu motor de busca favorito sempre que precisar procurar mais informações sobre uma característica CSS. Por exemplo, experimente pesquisar por "mdn color" e "mdn font-size"!

+
+ +

Módulos CSS

+ +

Como existem tantas coisas que você pode estilizar com CSS, a linguagem é dividida em módulos. Verá referência a esses módulos a medida que explora o MDN e muita das páginas da documentação são organizadas em torno de um módulo em particular. Por exemplo, poderia dar uma olhada na referência MDN para os módulos Backgrounds and Borders para descobrir qual é o seu objetivo, e quais diferentes propriedades e outras características ele contém. Você também encontrará links para a especificação CSS que define a tecnologia (veja abaixo).

+ +

Nesse ponto você não precisa se preocupar muito sobre como o CSS é estruturado. No entanto, isso pode tornar fácil achar informação se, por exemplo, você estiver ciente de que uma determinada propriedade provavelmente será encontrada entre outras coisas semelhantes e estiver, portanto, provavelmente na mesma especificação.  

+ +

Para um exemplo específico, vamos voltar ao módulo Backgrounds e Borders  — você pode achar que isso tem um senso lógico para as propriedades background-color e border-color serem definidas neste módulo. E, você está certo!

+ +

Especificações CSS

+ +

Todas as tecnologias de padrões web (HTML, CSS, JavaScript, etc.) são definidos em documentos gigantes chamados especificações (ou simplesmente "specs"), que são publicados por organizações de padrões (tais como {{glossary("W3C")}}, {{glossary("WHATWG")}}, {{glossary("ECMA")}}, ou {{glossary("Khronos")}}) e definem precisamente como essas tecnologias devem se comportar.

+ +

Com CSS não é diferente — ele é desenvolvido por um grupo dentro do W3C chamado CSS Working Group. Esse grupo é formado por representantes de fornecedores de navegadores web e outras companhias que tem interesse em CSS. Também existe outras pessoas, conhecidas como peritos convidados (invited experts), que agem como vozes independentes; eles não são associados como um membro de alguma organização.

+ +

Novas características CSS são desenvolvidas, ou especificadas, pelo CSS Working Group. As vezes, porque um navegador em particular está interessado em alguma capacidade, outras vezes, porque designers web e desenvolvedores estão perguntando por uma característica, e, algumas vezes, porque o Working Group em si tem identificado uma necessidade. O CSS está em constante desenvolvimento, com novas peculiaridades ficando disponíveis. Contudo, uma ideia chave sobre CSS é que todos trabalham pesado para nunca alterar as coisas de uma maneira que não quebrem os sites antigos. Um site construído no ano 2000, usando um CSS limitado da época, deverá ainda ser utilizável em um navegador moderno!

+ +

Como iniciante no CSS, é provável que você ache as especificações CSS impressionantes — eles são direcionados a engenheiros para implementar suporte aos recursos nos agentes de usuário (navegadores), não para desenvolvedores lerem com o intuito de entender CSS. Muitos desenvolvedores experientes preferem consultar a documentação do MDN ou outros tutoriais. No entanto, vale a pena saber que eles existem, entender a relação entre o CSS que você usa, suporte ao navegador (veja abaixo), e os specs (especificações).

+ +

Suporte do navegador

+ +

Uma vez que o CSS tenha sido especificado, então se torna útil para nós, em termos de desenvolvimento de páginas web, apenas se um ou mais navegadores implementá-los. Isso significa que o código foi escrito para transformar as instruções do nosso arquivo CSS em algo que possa ser mostrado na tela. Vamos olhar um pouco mais esse processo nas lições Como o CSS funciona. É inusitado implementarem uma característica ao mesmo tempo, e, geralmente, existe uma lacuna na qual se pode usar parte do CSS em alguns navegadores e em outros não. Por esse motivo, ser capaz de verificar o estado da implemtação é útil. Para cada página de propriedade no MDN, pode-se ver o estado dela, que se esta interessado. Assim, você saberá se pode usá-la em uma página.

+ +

A seguir, é apresentado o gráfico de dados compat para propriedade CSS font-family.

+ +

{{Compat("css.properties.font-family")}}

+ +

A seguir

+ +

Agora que você tem algum entendimento do que o CSS é, vamos ao Iniciando com CSS, onde pode começar a escrever alguma coisa, você mesmo.

+ +

{{NextMenu("Learn/CSS/First_steps/Getting_started", "Learn/CSS/First_steps")}}

+ +

Neste módulo

+ +
    +
  1. O que é CSS?
  2. +
  3. Começando com CSS
  4. +
  5. Como o CSS é estruturado
  6. +
  7. Como o CSS funciona
  8. +
  9. Usando o seu novo conhecimento
  10. +
diff --git a/files/pt-br/learn/css/first_steps/using_your_new_knowledge/index.html b/files/pt-br/learn/css/first_steps/using_your_new_knowledge/index.html new file mode 100644 index 0000000000..848524cba3 --- /dev/null +++ b/files/pt-br/learn/css/first_steps/using_your_new_knowledge/index.html @@ -0,0 +1,96 @@ +--- +title: Using your new knowledge +slug: Learn/CSS/First_steps/Using_your_new_knowledge +translation_of: Learn/CSS/First_steps/Using_your_new_knowledge +--- +

{{LearnSidebar}}{{PreviousMenu("Learn/CSS/First_steps/How_CSS_works", "Learn/CSS/First_steps")}}

+ +

Com o que você aprendeu nas últimas lições, você deve perceber que pode formatar simples documentos de texto utilizando CSS, implementado seu próprio estilo neles. Esta avaliação lhe dá a oportunidade de fazer exatamente isto.

+ + + + + + + + + + + + +
Pré-requisitos:Antes de tentar esta avaliação você deve ter passado pelo resto do módulo básico de CSS, além de também possuir uma compreensão básica de HTML (estude Introdução ao HTML).
Objetivo:Trabalhar um pouco de CSS e testar seus novos conhecimentos.
+ +

Ponto de partida

+ +

Você pode trabalhar com editor ao vivo abaixo, ou pode fazer o download do ponto de partida para trabalhar em seu próprio editor de texto. Esta é uma única página de HTML, além do ponto de partida no head do documento. Se preferir, você pode transferir este CSS para um arquivo separado quando criar o exemplo no seu computador. Ou ainda, você pode utilizar uma ferramenta online como por exemplo, o CodePenjsFiddle, ou Glitch para realizar estas tarefas..

+ +
+

Nota: Se ficar emperrado,  nos procure por ajuda — veja a seção Assessment or further help no final da página.

+
+ +

Trabalhando com CSS

+ +

O seguite exemplo mostra uma biografia, o qual foi estilizado com CSS. As propriedades CSS que eu usei foram as mencionadas abaixo — cada uma está lincada a sua página de propriedades em MDN, a qual dará mais exemplos do uso dela.

+ + + +

Eu usei uma mistura de seletores, estilizando elementos como h1 e h2, mas também criando uma classe para o título da profissão e estilizando ela.

+ +

Use CSS para mudar como esta biografia aparece, alterando valores das propriedades que eu utilizei.

+ +
    +
  1. Faça o cabeçalho rosa, usando a chave de cor CSS hotpink.
  2. +
  3. Dê ao cabeçalho um pontilhado de tamanho 10px {{cssxref("border-bottom")}} e que utiliza a chave de cor CSS  purple.
  4. +
  5. Faça o cabeçalho nível 2 em itálico.
  6. +
  7. Dê ao ul usado para informações de contato uma {{cssxref("background-color")}} #eeeeee, e uma {{cssxref("border")}}  roxa sólida com de tamanho 5px. Implemente um {{cssxref("padding")}} para empurrar o conteúdo para longe da borda.
  8. +
  9. Torne os links verdes ao passar o mouse por cima deles.
  10. +
+ +

Você deve acabar com algo parecido com esta imagem.

+ +

Screenshot of how the example should look after completing the assessment.

+ +

Após isto, tente pesquisar algumas propriedades não mencionadas nesta página em MDN CSS referências e se aventure!

+ +

Lembre-se de que não há resosta errada aqui — neste momento de seu aprendizado, você pode se dar ao luxo de de se divertir um pouco.

+ +

{{EmbedGHLiveSample("css-examples/learn/getting-started/biog.html", '100%', 1600)}} 

+ +

Assessment or further help

+ +

Se gostaria de ter seu trabalho avaliado, ou se ficou emperrado e gostaria de ajuda:

+ +
    +
  1. Coloque seu trabalho num editor de texto compartilhado online tal como o CodePenjsFiddle, ou Glitch.
  2. +
  3. Escreva um post perguntando por avaliação e/ou ajuda em MDN Discourse forum Learning category. Seu post deve incluir: +
      +
    • Um título descritivo, tal como "Avaliação desejada para primeiros passos em CSS".
    • +
    • Detalhes do que você já tentou, e o que gostaria que  ós fizéssemos, p.e. se você está emperrado e precisa de ajuda, ou se deseja uma avalição.
    • +
    • Um link para o exemplo que você deseja ser avaliadao ou precisa de ajuda, em um editor online compartilhado (como mencionado no passo 1 acima). Esta é uma boa prática a se desenvolver — é muito difícil ajudar alguém com um problema de computação se não é possível ver o código dessa pessoa.
    • +
    • Um link para a atual págia de tarefa ou avaliaçãopara que possamos ver a questão que você está com dúvida.
    • +
    +
  4. +
+ +

O que vem a seguir?

+ +

Parabéns por terminar seu primeiro módulo. Agora você deve ter uma boa compreensão geral de CSS, e ser capaz de entender boa parte do que acontece numa folha de estilos. No próximo módulo, CSS building blocks, iremos dar uma olhada com mais profundidade em várias áreas chave.

+ +

{{PreviousMenu("Learn/CSS/First_steps/How_CSS_works", "Learn/CSS/First_steps")}}

+ +

Neste módulo

+ +
    +
  1. O que é CSS?
  2. +
  3. Começando com CSS
  4. +
  5. Como o CSS é estruturado
  6. +
  7. Como o CSS funciona
  8. +
  9. Utilizando seu novo conhecimento
  10. +
diff --git a/files/pt-br/learn/css/howto/css_perguntas_frequentes/index.html b/files/pt-br/learn/css/howto/css_perguntas_frequentes/index.html new file mode 100644 index 0000000000..f3febd4637 --- /dev/null +++ b/files/pt-br/learn/css/howto/css_perguntas_frequentes/index.html @@ -0,0 +1,245 @@ +--- +title: CSS - Perguntas frequentes +slug: Learn/CSS/Howto/CSS_Perguntas_Frequentes +tags: + - CSS + - Exemplo + - FAQ + - Guía + - Perguntas + - Perguntas Frequentes + - Web +translation_of: Learn/CSS/Howto/CSS_FAQ +--- +

Por que meu CSS, que é válido, não é renderizado corretamente?

+ +

Navegadores usam a declaração de DOCTYPE para decidir se devem exibir o documento usando um modo compatível com os padrões da web ou com padrões de navegadores antigos. Usar corretamente a declaração de um DOCTYPE moderno no início do seu documento HTML melhorará a forma como o navegador trata os padrões utilizados no documento.

+ +

Navegadores modernos possuem dois principais modos de renderização:

+ + + +

Navegadores baseados na engine Gecko possuem um terceiro modo de renderização; Modo de "quase padrões" (Almost Standards Mode), que renderiza as páginas seguindo regras do Modo de padrões, porém considerando algumas poucas peculiaridades encontradas em páginas para navegadores antigos.

+ +

Esta é uma lista das declarações de DOCTYPE mais usadas e que acionarão o modo de padrões ou de "quase padrões":

+ +
<!DOCTYPE html> /* Este é o doctype HTML5. Levando em consideração que
+                   navegadores modernos possuem um parser de HTML5, o
+                   uso desta declaração é recomendada */
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
+"http://www.w3.org/TR/html4/loose.dtd">
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+ +

Sempre que possível, use a declaração de DOCTYPE HTML5.

+ +

Por que meu CSS, que é válido, não é renderizado?

+ +

Abaixo temos algumas das possíveis causas:

+ + + +

Qual a diferença entre id e class?

+ +

Elementos HTML podem ter um atributo id e/ou um atributo class. O atributo id designa um nome ao elemento ao qual este é aplicado, e para que a marcação seja válida, deverá haver no documento apenas um elemento com o nome designado (Por exemplo: Caso você designe o nome janela a um elemento, nenhum outro elemento poderá ter o nome janela).

+ +

O atributo class designa um ou vários nomes de classes as quais um elemento pertence. Diferentemente do valor designado no atributo id, os nomes designados em class podem ser reutilizados em outros elementos no documento. De qualquer forma, CSS permite que você aplique estilos tanto para uma id particular quanto para classes.

+ +

Algumas dicas de quando usar id e quando usar class:

+ + + +

Geralmente é recomendável que se utilize classes sempre que possível, utilizando ids apenas quando absolutamente necessário para usos específicos (como conectar um label a um elemento de formulário, ou para estilizar elementos que necessicam ser semanticamente únicos). Abaixo estão descritas algumas vantagens em utilizar classes como forma principal de estilização:

+ + + +
+

Nota: Veja Seletores para mais informações.

+
+ +

Como eu redefino o valor padrão de uma propriedade?

+ +

Inicialmente CSS não propiciava a diretiva "default" e a única forma de redefinir o valor padrão de uma propriedade era expliciatamente redeclarando aquela propriedade. Por exemplo:

+ +
/* A cor padrão do cabeçalho é preta */
+h1 { color: red; }
+h1 { color: black; }
+ +

Isso mudou com CSS 2; a diretiva initial agora é um valor válido para uma propriedade CSS. Ela redefine tal propriedade para seu valor padrão, o qual é definido nas especificações CSS para tal propriedade.

+ +
/* A cor padrão do cabeçalho é preta */
+h1 { color: red; }
+h1 { color: initial; }
+ +

Como eu derivo um estilo de outro?

+ +

CSS não exatamente permite que um estilo seja definido com os termos de outro. (Veja as notas de Eric Meyer sobre a posição do grupo de trabalho a respeito do assunto). Entretanto, é possível atingir o mesmo efeito designando diversas classes a um elemento, e Variáveis CSS agora providenciam uma forma de definir informações sobre um estilo em um lugar e reutilizar estas informações em diversos outros lugares.

+ +

Como eu aplico diversas classes a um elemento?

+ +

Elementos HTML podem ter diversas classes designadas a si, com as classes sendo listadas no atributo class, tendo um espaço em branco separando cada uma.

+ +
<style type="text/css">
+  .news { background: black; color: white; }
+  .today { font-weight: bold; }
+</style>
+
+<div class="news today">
+... content of today's news ...
+</div>
+
+ +

Caso a mesma propriedade seja declara em mais de uma regra, o conflito é resolvido primeiro pela ordem de especificidade e depois através da ordem das declarações CSS, com o último valor definido da propriedade sendo considerado. A ordem em que o nome das classes aparece no atributo class é irrelevante.

+ +

Por que minhas regras de estilização não funcionam corretamente?

+ +

Regras de estilização, mesmo que sejam semanticamente corretas, podem não ser aplicadas em determinadas situações. Você pode utilizar o visualizador de regras CSS do Inspetor de DOM para resolver problemas deste tipo, mas as ocasiões mais frequentes onde regras de estilização são ignoradas estão listadas abaixo.

+ +

Hierarquia dos elementos HTML

+ +

A forma como estilos CSS são aplicados a elementos HTML depende também da hierarquia dos elementos HTML. É importante lembrar que a regra aplicada a um descendente sobrepõe a regra do pai, independente de qualquer especificidade ou prioridade das regras CSS.

+ +
<style type="text/css">
+  .news { color: black; }
+  .corpName { font-weight: bold; color: red; }
+</style>
+
+<!-- O texto do item news é preto, mas o nome da corporação é vermelho e em negrito -->
+<div class="news">
+   (Reuters) <span class="corpName">General Electric</span> (GE.NYS) announced on Thursday...
+</div>
+
+ +

No caso de hierarquias HTML complexas, se uma regra parece ser ignorada, verifique se o elemento está dentro de outro elemento com um estilo diferente.

+ +

Regra de estilização explicitamente redefinida

+ +

Em folhas de estilo CSS, a ordem é importante. Se você definir uma propriedade e logo depois redefinir a mesma propriedade, a última regra definida será considerada.

+ +
<style>
+  #stockTicker { font-weight: bold; }
+  .stockSymbol { color: red; }
+  /*  outras regras             */
+  /*  outras regras             */
+  /*  outras regras             */
+  .stockSymbol { font-weight: normal; }
+</style>
+
+<!-- Boa parte do texto está em negrito, exceto "GE", que é vermelho e não está em negrito -->
+<div id="stockTicker">
+   NYS: <span class="stockSymbol">GE</span> +1.0 ...
+</div>
+
+ +

Para evitar que este tipo de problema, tente definir regras apenas uma vez para um determinado seletor e agrupe as regras para aquele seletor.

+ +

Uso de uma propriedade reduzida

+ +

Utilizar propriedades reduzidas para definir regra de estilização é interessante pois permite definir diversas propriedade de uma regra em uma sintaxe compacta e que permite otimizar o tamanho da folha de estilos. Utilizar propriedades reduzidas para definir apenas uma propriedade é permitido, mas deve ser lembrado que atributos da propriedade não definidos são redefinidos para seu valor padrão. Ou seja, isso pode acabar sobrepondo regras anteriormente definidas implicitamente..

+ +
<style>
+   #stockTicker { font-size: 12px; font-family: Verdana; font-weight: bold; }
+   .stockSymbol { font: 14px Arial; color: red; }
+</style>
+
+<div id="stockTicker">
+   NYS: <span class="stockSymbol">GE</span> +1.0 ...
+</div>
+
+ +

No exemplo anterior o problema ocorre em regras pertencentes a diferentes elementos. Mas também poderia acontecer para o mesmo elemento, pois a ordem das regras é importante.

+ +
#stockTicker {
+   font-weight: bold;
+   font: 12px Verdana;  /* font-weight agora está definido como "normal" */
+}
+
+ +

Uso do seletor *

+ +

O seletor curinga * faz referência a qualquer elemento, e deve ser usado com cuidado.

+ +
<style>
+   body * { font-weight: normal; }
+   #stockTicker { font: 12px Verdana; }
+   .corpName { font-weight: bold; }
+   .stockUp { color: red; }
+</style>
+
+<div id="section">
+   NYS: <span class="corpName"><span class="stockUp">GE</span></span> +1.0 ...
+</div>
+
+ +

No exemplo acima, o seletor * aplica a regra para todos os elementos dentro de body, em qualquer nível hierarquico, incluindo a classe .stockUp. Sendo assim a regra font-weight: bold; aplicada à classe .corpName é sobreposta por font-weight: normal; aplicada a todos os elementos dentro de body.

+ +

O uso do seletor * também deve ser minimizado por ser um seletor lento, especialmente quando não utilizado como o primeiro elemento de um seletor. Este seletor deve ser evitado o máximo possível.

+ +

Especificidade em CSS

+ +

Quando multiplas regras são aplicadas a um elemento, a regra a ser renderizada depende de sua especificidade. O estilo inline (regras de estilo definidas no atributo style de um elemento HTML) tem a mais alta especificidade e irá sobrepor qualquer seletor. Seletores de ID tem a segunda mais alta especificidade, com seletores de classes vindo logo após e, eventualmente, seletores de elementos (tags). Tendo isso em mente, a cor do texto da {{htmlelement("div")}} abaixo terá a cor vermelha.

+ +
<style>
+   div { color: black; }
+   #orange { color: orange; }
+   .green { color: green; }
+</style>
+
+<div id="orange" class="green" style="color: red;">Isso é vermelho</div>
+
+ +

As regras se tornam mais complicadas quando o seletor tem diversas partes. Informações mais detalhadas sobre como a especificidade de seletores é calculada podem ser encontradas nas Especificações CSS 2.1, capítulo 6.4.3.

+ +

O que as propriedades -moz-*, -ms-*, -webkit-*, -o-* e -khtml-* fazem?

+ +

Estas propriedades, chamadas propriedades prefixadas, são extenções ao padrão CSS. Elas permitem o uso de recursos experimentais e fora dos padrões em navegadores sem poluir o namespace convencional, prevenindo que incompatibilidades entre implementações experimentais e fora dos padrões surjam quando os padrões CSS forem expandidos.

+ +

Apesar do vasto uso na web, o uso de propriedades prefixadas não é recomendado em ambiente de produção. O uso indiscriminado de funcionalidades experimentais ou não-padrão pode causar problemas de compatibilidade futuros (como uma funcionalidade experimental mudando de nome, ou tendo o mesmo nome de uma outro funcionalidade que no passado tinha uma finalidade completamente diferente) e não renderizar páginas de forma correta em diferentes navegadores. Outro problema muito comum encontrado pelo uso indiscriminado de propriedades prefixadas é a declaração de regras que acabam se tornando exclusivas para determinadas engines, quebrando a renderização em outros navegadores, mesmo estes navegadores dando suporte à propriedade padrão não-prefixada (Por exemplo, apenas a propriedade -webkit-border-radius sendo usada em uma regra ao invés de border-radius, que é suportada por todos os navegadores, inclusive os baseados em webkit).

+ +

Para amenizar os problemas de incompatibilidade gerados pelo uso de propriedades prefixadas (principalmente -webkit-), foi estabelecido o Compatibility Living Standard, o qual sugere um conjunto de propriedades -webkit- que navegadores (mesmo não utilizando a engine webkit) devem suportar. Outra medida que vem sendo tomada por desenvolvedores de navegadores é abandonar o suporte a propriedades prefixadas em versões estáveis dos navegadores, mantendo suporte a tais propriedades apenas emNightly Builds e similares, desencorajando o uso em ambiente de produção.

+ +

Caso você precise usar propriedades prefixadas em seu trabalho, você deve declarar primeiramente as propriedades prefixadas e, por último, declarar a versão padrão não-prefixada da propriedade anteriormente declara, garantindo que o navegador utilize a versão especificada nos padrões assim que suportado. Por exemplo:

+ +
-ms-transform: rotate(90deg);
+-webkit-transform: rotate(90deg);
+transform: rotate(90deg);
+ +
+

Nota: Para mais informações em como lhe dar com propriedades prefixadas, veja Lidando com problemas comuns em HTML e CSS — Lidando com prefixos CSS do nosso módulo Teste Cross-browsing.

+
+ +
+

Nota: Veja a página Extenções CSS Mozilla para mais informações sobre propriedades CSS prefixadas da Mozilla.

+
+ +

Como z-index está relacionado a posicionamento?

+ +

A propriedade z-index especifica a ordem dos elementos da pilha.

+ +

Um elemento com z-index/ordem na pilha maior sempre será renderizado à frente de um elemento com um z-index/ordem de pilha menor. z-index funcionará apenas em elementos que tenham uma posição especificada (Ou seja, só funcionará caso o elemento tenha position:absoluteposition:relative ou position:fixed).

+ +
+

Nota: Para mais informações, veja nosso artigo de aprendizado sobre Posicionamento, e em particular a seção Introduzindo z-index.

+
diff --git a/files/pt-br/learn/css/howto/index.html b/files/pt-br/learn/css/howto/index.html new file mode 100644 index 0000000000..01e5fe9373 --- /dev/null +++ b/files/pt-br/learn/css/howto/index.html @@ -0,0 +1,92 @@ +--- +title: Use CSS to solve common problems +slug: Learn/CSS/Howto +tags: + - Beginner + - CSS + - Learn + - NeedsTranslation + - TopicStub +translation_of: Learn/CSS/Howto +--- +
{{LearnSidebar}}
+ +

The following links point to solutions to common everyday problems you'll need to solve with CSS.

+ +

Common use cases

+ +
+ + + +
+ +

Uncommon or advanced techniques

+ +

Beyond the basics, CSS is allows very advanced design techniques. These articles help you tackle the hardest use cases you may face.

+ +

General

+ + + +

Advanced effects

+ + + +

Layout

+ + + +

See also

+ +

CSS FAQ — A collection of smaller bits of information, covering a variety of topics from debugging to selector usage.

-- cgit v1.2.3-54-g00ecf