From 68fc8e96a9629e73469ed457abd955e548ec670c Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:49:58 +0100 Subject: unslug pt-br: move --- .../cascade_and_inheritance/index.html | 345 ++++++++++ files/pt-br/learn/css/building_blocks/index.html | 83 +++ .../css/building_blocks/the_box_model/index.html | 343 ++++++++++ .../learn/css/css_layout/fluxo_normal/index.html | 95 --- .../css/css_layout/intro_leiaute_css/index.html | 707 --------------------- .../learn/css/css_layout/introduction/index.html | 707 +++++++++++++++++++++ .../css_layout/layout_de_varias_colunas/index.html | 414 ------------ .../css_layout/multiple-column_layout/index.html | 414 ++++++++++++ .../learn/css/css_layout/normal_flow/index.html | 95 +++ .../first_steps/como_css_e_estruturado/index.html | 502 --------------- .../css/first_steps/getting_started/index.html | 265 ++++++++ .../first_steps/how_css_is_structured/index.html | 502 +++++++++++++++ .../learn/css/first_steps/iniciando/index.html | 265 -------- .../learn/css/first_steps/o_que_e_css/index.html | 127 ---- .../learn/css/first_steps/what_is_css/index.html | 127 ++++ files/pt-br/learn/css/howto/css_faq/index.html | 245 +++++++ .../css/howto/css_perguntas_frequentes/index.html | 245 ------- files/pt-br/learn/css/index.html | 61 ++ files/pt-br/learn/css/styling_text/index.html | 48 ++ .../css/styling_text/styling_lists/index.html | 272 ++++++++ 20 files changed, 3507 insertions(+), 2355 deletions(-) create mode 100644 files/pt-br/learn/css/building_blocks/cascade_and_inheritance/index.html create mode 100644 files/pt-br/learn/css/building_blocks/index.html create mode 100644 files/pt-br/learn/css/building_blocks/the_box_model/index.html delete mode 100644 files/pt-br/learn/css/css_layout/fluxo_normal/index.html delete mode 100644 files/pt-br/learn/css/css_layout/intro_leiaute_css/index.html create mode 100644 files/pt-br/learn/css/css_layout/introduction/index.html delete 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/multiple-column_layout/index.html create mode 100644 files/pt-br/learn/css/css_layout/normal_flow/index.html delete 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/getting_started/index.html create mode 100644 files/pt-br/learn/css/first_steps/how_css_is_structured/index.html delete mode 100644 files/pt-br/learn/css/first_steps/iniciando/index.html delete 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/what_is_css/index.html create mode 100644 files/pt-br/learn/css/howto/css_faq/index.html delete mode 100644 files/pt-br/learn/css/howto/css_perguntas_frequentes/index.html create mode 100644 files/pt-br/learn/css/index.html create mode 100644 files/pt-br/learn/css/styling_text/index.html create mode 100644 files/pt-br/learn/css/styling_text/styling_lists/index.html (limited to 'files/pt-br/learn/css') diff --git a/files/pt-br/learn/css/building_blocks/cascade_and_inheritance/index.html b/files/pt-br/learn/css/building_blocks/cascade_and_inheritance/index.html new file mode 100644 index 0000000000..b3988ca69b --- /dev/null +++ b/files/pt-br/learn/css/building_blocks/cascade_and_inheritance/index.html @@ -0,0 +1,345 @@ +--- +title: Cascade and inheritance +slug: Aprender/CSS/Construindo_blocos/Cascade_and_inheritance +translation_of: Learn/CSS/Building_blocks/Cascade_and_inheritance +--- +
{{LearnSidebar}}{{NextMenu("Learn/CSS/Building_blocks/Selectors", "Learn/CSS/Building_blocks")}}
+ +

O objetivo desta lição é desenvolver sua compreensão para alguns dos conceitos mais fundamentais de CSS - cascata, especificidade e herança - que controlam como o CSS é aplicado ao HTML e como os conflitos são resolvidos.

+ +

Embora esta lição possa parecer menos pouco relevante e mais acadêmico do que algumas outras partes do curso, a compreensão desses itens (cascata, especificidade e herança), poupará muito tempo no futuro! Recomendamos que você trabalhe nesta seção com cuidado e verifique se entendeu os conceitos antes de prosseguir.

+ + + + + + + + + + + + +
Pré-requisitos: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.)
Objectivo:Aprender sobre cascata e especificidade, e como funciona a herança em CSS.
+ +

Regras de Conflitos

+ +

CSS - Cascading Style Sheets, cascata (a primeira palavra) é muito importante compreender - a maneira como a cascata se comporta é a chave para entender CSS.

+ +

Em algum momento, você estará trabalhando em um projeto e descobrirá que o CSS que você pensou que deveria ser aplicado a um elemento não está funcionando. Normalmente, o problema é que você criou duas regras que poderiam se aplicar ao mesmo elemento. A cascata e o conceito intimamente relacionado com especificidade que são mecanismos que controlam qual regra se aplica quando existe tal conflito. A regra que define o estilo do seu elemento pode não ser a esperada, portanto, você precisa entender como esses mecanismos funcionam.

+ +

Também é importante aqui é o conceito de herança, o que significa que algumas propriedades CSS por padrão herdam os valores definidos no elemento pai do elemento atual, e outras não. Isso também pode causar algum comportamento que você não esperava.

+ +

Vamos começar dando uma olhada rápida nas nestes itens com os quais estamos lidando (cascata, especificidade e herança), então vamos ver como elas interagem entre si e com o CSS. Isso pode parecer um conjunto de conceitos difíceis de entender, mas a medida que você pratica mais a escrita de CSS, o funcionamento vai se tornando mais óbvio para você.

+ +

The cascade - A Cascata

+ +

Stylesheets cascade (Cascata) — em um nível muito simples, significa que a ordem das regras CSS é importante; quando se aplicam duas regras com especificidade igual, a que vier por último no CSS é a que será usada.

+ +

No exemplo abaixo, temos duas regras que podem ser aplicadas ao h1. O h1 acaba tendo a cor azul - essas regras têm um seletor idêntico e, portanto, carregam a mesma especificidade, portanto, o último na ordem de origem vence.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/cascade-simple.html", '100%', 400)}} 

+ +

Specificity - Especificidade

+ +

A especificidade é como o navegador decide/verifica qual regra se aplica se várias regras têm seletores diferentes, que poderiam ser aplicadas ao mesmo elemento. É basicamente uma medição de qual das regras/caracteristicas específica será a mais indicada/específica de um seletor:

+ + + +

Hora do exemplo! Abaixo, temos novamente duas regras que podem ser aplicadas ao h1. O h1 abaixo acaba sendo colorido em vermelho - o seletor de classe dá a sua regra uma especificidade mais alta e, portanto, será aplicada mesmo que a regra com o seletor de elemento apareça mais abaixo na ordem de origem.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/specificity-simple.html", '100%', 500)}} 

+ +

Explicaremos a pontuação de especificidade mais tarde.

+ +

Inheritance - Herança

+ +

A herança também precisa ser entendida neste contexto - alguns valores de propriedade CSS definidos em elementos pais são herdados por seus elementos filhos e outros não.

+ +

Por exemplo, se você definir uma cor e uma família de fontes em um elemento, todos os elementos dentro dele também serão estilizados com essa cor e fonte, a menos que você tenha aplicado cores e valores de fonte diferentes diretamente a eles.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/inheritance-simple.html", '100%', 550)}} 

+ +

Algumas propriedades não herdam - por exemplo, se você definir um {{cssxref ("width")}} de 50% em um elemento, todos os seus descendentes não terão uma largura de 50% da largura de seus pais. Se fosse esse o caso, CSS seria muito frustrante de usar!

+ +
+

Note: Nas páginas de referência de propriedade CSS do MDN, você pode encontrar uma caixa de informações técnicas, geralmente na parte inferior da seção de especificações, que lista uma série de pontos de dados sobre essa propriedade, incluindo se ela é herdada ou não. Veja o color property Specifications section (seção de especificações de propriedade de cor) , por exemplo.

+
+ +

Entendendo como os conceitos funcionam juntos

+ +

Esses três conceitos juntos controlam que caractersticas CSS se aplicam a qual elemento; nas seções a seguir, veremos como eles funcionam juntos. Às vezes pode parecer um pouco complicado, mas você começará a entende-los conforme for ficando mais experiente com CSS, e você sempre poderá consultar os detalhes se esquecer! Mesmo os desenvolvedores experientes não se lembram de todos os detalhes.

+ +

O vídeo a seguir mostra como você pode usar o Firefox DevTools para inspecionar a cascata, a especificidade de uma página e muito mais:

+ +

{{EmbedYouTube("Sp9ZfSvpf7A")}}

+ +

Entendendo Herança

+ +

Começaremos com herança. No exemplo abaixo, temos um {{HTMLElement ("ul")}}, com dois níveis de listas não ordenadas aninhadas dentro dele. Demos ao <ul> externo uma borda, preenchimento e uma cor de fonte.

+ +

A cor foi aplicada aos filhos diretos, mas também aos filhos indiretos - os filhos imediatos <li> são aqueles dentro da primeira lista aninhada. Em seguida, adicionamos uma classe especial à segunda lista aninhada e aplicamos uma cor diferente a ela. Isso então é herdado por meio de seus filhos.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/inheritance.html", '100%', 700)}} 

+ +

Coisas como larguras (conforme mencionado acima), margens, preenchimento e bordas não são herdadas. Se uma borda fosse herdada pelos filhos de nossa lista, cada lista e cada item da lista ganhariam uma borda - provavelmente não é um efeito que desejaríamos!

+ +

Quais propriedades são herdadas por padrão e quais não são, depende do bom senso.

+ +

Controlando Herança

+ +

CSS fornece quatro valores especiais de propriedades universais para controlar a herança. Cada propriedade CSS aceita esses valores.

+ +

{{cssxref("inherit")}}

+ +

    Define o valor da propriedade aplicada a um elemento selecionado para ser o mesmo de          seu elemento pai. Efetivamente, isso "ativa a herança".

+ +

{{cssxref("initial")}}

+ +
+
Define o valor da propriedade aplicada a um elemento selecionado para o valor inicial dessa propriedade.
+
{{cssxref("unset")}}
+
Restaura a propriedade com seu valor natural, o que significa que se a propriedade é herdada naturalmente, ela age como herdada, caso contrário, ela age como inicial.
+
+ +
+

Note: Temos um comando mais recente, {{cssxref("revert")}}, mas nem todos os navegadores suportam

+
+ +
+

Note: veja {{SectionOnPage("/en-US/docs/Web/CSS/Cascade", "Origin of CSS declarations")}}para obter mais informações sobre como cada um deles funcionam.

+
+ +

Podemos ver uma lista de links e explorar como funcionam os valores universais. O exemplo ao vivo abaixo permite que você brinque com o CSS e veja o que acontece quando você faz alterações. Usar/modificar o código é realmente a melhor maneira de se familiarizar com HTML e CSS.

+ +

Por exemplo:

+ +
    +
  1. O segundo item da lista tem a classe my-class-1 aplicada. Isso define a cor do elemento <a> aninhado dentro para herdar. Se você remover a regra, como ela muda a cor do link?
  2. +
  3. Você consegue entende por que o terceiro e o quarto links são da mesma cor? Verifique a descrição dos valores acima se não.
  4. +
  5. Qual dos links mudará de cor se você definir uma nova cor para o elemento <a> - por exemplo, um {color: red; }?
  6. +
+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/keywords.html", '100%', 700)}} 

+ +

Redefinindo todos os Valores de Propriedade

+ +

A propriedade abreviada CSS all pode ser usada para aplicar um desses valores de herança a (quase) todas as propriedades de uma vez. Seu valor pode ser qualquer um dos valores de herança (herdar, inicial, não definido ou reverter). É uma maneira conveniente de desfazer as alterações feitas nos estilos para que você possa voltar a um ponto de partida conhecido antes de iniciar novas alterações.

+ +

No exemplo abaixo, temos duas aspas em bloco. O primeiro tem um estilo aplicado ao próprio elemento blockquote, o segundo tem uma classe aplicada ao blockquote que define o valor de all (todos) como unset (indefinido).

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/all.html", '100%', 700)}} 

+ +

Tente definir o valor de todos para alguns dos outros valores disponíveis e observe qual é a diferença.

+ +

Compreendendo Cascata

+ +

Agora entendemos por que um parágrafo aninhado profundamente na estrutura do seu HTML tem a mesma cor do CSS aplicado ao corpo e, a partir das lições introdutórias, entendemos como alterar o CSS aplicado a algo em qualquer ponto do documento - seja atribuindo CSS a um elemento ou criando uma classe. Agora daremos uma olhada apropriada em como a cascata define quais regras CSS se aplicam quando mais de uma coisa pode estilizar um elemento.

+ +

Há três fatores a serem considerados, listados aqui em ordem crescente de importância. Os posteriores anulam os anteriores:

+ +
    +
  1. Ordem da Fonte
  2. +
  3. Especificidade
  4. +
  5. Importância
  6. +
+ +

Vamos dar uma olhada neles para ver como os navegadores descobrem exatamente o que CSS deve ser aplicado.

+ +

Ordem da Fonte (origem)

+ +

Já vimos como a ordem da fonte é importante para a cascata. Se você tiver mais de uma regra, que tenha exatamente o mesmo peso, a que vier por último no CSS será a vencedora. Você pode pensar nisso como regras que estão mais próximas do próprio elemento, sobrescrevendo as anteriores, até que a última vença e dê estilo ao elemento.

+ +

Especificidade

+ +

Depois de compreender o fato de que a ordem da fonte é importante, em algum momento você se deparará com uma situação em que saberá que uma regra vem depois na folha de estilo, mas uma regra anterior conflitante é aplicada. Isso ocorre porque a regra anterior tem uma especificidade mais alta - é mais específica e, portanto, está sendo escolhida pelo navegador como a que deve estilizar o elemento.
+
+ Como vimos anteriormente nesta lição, um seletor de classe tem mais peso do que um seletor de elemento, portanto, as propriedades definidas na classe substituirão aquelas aplicadas diretamente ao elemento.
+
+ Algo a se notar aqui é que, embora estejamos pensando em seletores e nas regras que são aplicadas ao que eles selecionam, não é a regra inteira que é substituída, apenas as propriedades que são iguais.

+ +

Esse comportamento ajuda a evitar a repetição em seu CSS. Uma prática comum é definir estilos genéricos para os elementos básicos e, em seguida, criar classes para aqueles que são diferentes. Por exemplo, abaixo definimos estilos genéricos para títulos de nível 2 e, em seguida, criamos algumas classes que alteram apenas algumas das propriedades e valores. Os valores definidos inicialmente são aplicados a todos os títulos, depois os valores mais específicos são aplicados aos títulos com as classes.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/mixing-rules.html", '100%', 700)}} 

+ +

Vamos agora dar uma olhada em como o navegador calculará a especificidade. Já sabemos que um seletor de elemento tem baixa especificidade e pode ser substituído por uma classe. Essencialmente, um valor em pontos é concedido a diferentes tipos de seletores, e somar esses pontos dá a você o peso daquele seletor específico, que pode então ser avaliado em relação a outras combinações potenciais.

+ +

A quantidade de especificidade que um seletor tem é medida usando quatro valores (ou componentes) diferentes, que podem ser considerados como milhares, centenas, dezenas e uns - quatro dígitos únicos em quatro colunas:

+ +
    +
  1. Thousands: marque um nesta coluna se a declaração estiver dentro de um atributo {{htmlattrxref ("style")}}, também conhecido como estilos embutidos. Essas declarações não têm seletores, portanto, sua especificidade é sempre simplesmente 1000.
  2. +
  3. Hundreds: marque um nesta coluna para cada seletor de ID contido no seletor geral.
  4. +
  5. Tens: marque um nesta coluna para cada seletor de classe, seletor de atributo ou pseudoclasse contido no seletor geral.
  6. +
  7. Ones: marque um nesta coluna para cada seletor de elemento ou pseudoelemento contido dentro do seletor geral.
  8. +
+ +
+

Note: O Seletor universal (*), combinadores (+, >, ~, ' '), e pseudo-classe de negação (:not) não tem efeito de especificidade.

+
+ +

A tabela a seguir mostra alguns exemplos isolados para colocá-lo no clima. Experimente passar por eles e certifique-se de entender por que eles têm a especificidade que demos a eles. Ainda não cobrimos os seletores em detalhes, mas você pode encontrar detalhes de cada seletor em MDN  selectors reference.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SelectorThousandsHundredsTensOnesTotal specificity
h100010001
h1 + p::first-letter00030003
li > a[href*="en-US"] > .inline-warning00220022
#identifier01000100
No selector, with a rule inside an element's {{htmlattrxref("style")}} attribute10001000
+ +

Antes de prosseguirmos, vejamos um exemplo em ação.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/specificity-boxes.html", '100%', 700)}} 

+ +

Então, o que está acontecendo aqui? Em primeiro lugar, estamos interessados ​​apenas nas primeiras sete regras deste exemplo e, como você notará, incluímos seus valores de especificidade em um comentário antes de cada uma.

+ + + +
    +
+ +
+

Note: Este foi apenas um exemplo aproximado para facilitar a compreensão. Na realidade, cada tipo de seletor tem seu próprio nível de especificidade que não pode ser substituído por seletores com um nível de especificidade inferior. Por exemplo, um milhão de seletores de classe combinados não seriam capazes de sobrescrever as regras de um seletor de id.

+ +

Uma forma mais precisa de avaliar a especificidade seria pontuar os níveis de especificidade individualmente começando do mais alto e passando para o mais baixo quando necessário. Somente quando há um empate entre as pontuações do seletor dentro de um nível de especificidade, você precisa avaliar o próximo nível abaixo; caso contrário, você pode desconsiderar os seletores de nível de especificidade inferior, pois eles nunca podem substituir os níveis de especificidade mais altos.

+
+ +

! Importante

+ +

Existe uma parte especial do CSS que você pode usar para ignorar todos os cálculos acima, no entanto, você deve ter muito cuidado ao usá-la -! Importante. Isso é usado para tornar uma determinada propriedade e valor a coisa mais específica, substituindo assim as regras normais da cascata.
+
+ Dê uma olhada neste exemplo onde temos dois parágrafos, um dos quais tem um ID.

+ +

{{EmbedGHLiveSample("css-examples/learn/cascade/important.html", '100%', 700)}} 

+ +

Vamos examinar isso para ver o que está acontecendo - tente remover algumas das propriedades para ver o que acontece e se você tiver dificuldade de entender:

+ +
    +
  1. Você verá que os valores da terceira regra {{cssxref ("color")}} e {{cssxref ("padding")}} foram aplicados, mas o {{cssxref ("background-color")}} não foram?. Por quê? Na verdade, todos os três devem ser aplicados, porque as regras posteriores na ordem de origem geralmente substituem as regras anteriores.
  2. +
  3. No entanto, as regras acima vencem, porque os seletores de classe têm uma especificidade mais alta do que os seletores de elemento.
  4. +
  5. Ambos elementos tem {{htmlattrxref("class")}} de better (melhor), mas o segundo tem um id {{htmlattrxref("id")}} que é mais forte. Como os IDs têm uma especificidade ainda maior do que as classes (você só pode ter um elemento com cada ID exclusivo em uma página, mas muitos elementos com a mesma classe - os seletores de ID são muito específicos no que se destinam), a cor de fundo vermelha e A borda preta de 1 pixel deve ser aplicada ao segundo elemento, com o primeiro elemento recebendo a cor de fundo cinza, e sem borda, conforme especificado pela classe.
  6. +
  7. O segundo elemento obtém a cor de fundo vermelha, mas sem borda. Por quê? Por causa da declaração! Important na segunda regra - incluindo isso depois de border: none significa que essa declaração vai superar o valor de border na regra anterior, embora o ID tenha uma especificidade mais alta.
  8. +
+ +
+

Note: A única maneira de sobrescrever essa declaração! Importante seria incluir outra declaração! Importante em uma declaração com a mesma especificidade posteriormente na ordem de origem, ou uma com uma especificidade mais alta.

+
+ +

É útil saber que! Important existe para que você saiba o que é quando o encontrar no código de outras pessoas. No entanto, recomendamos enfaticamente que você nunca o use, a menos que seja absolutamente necessário. ! mudanças importantes na maneira como a cascata normalmente funciona, portanto, pode tornar a depuração de problemas CSS realmente difícil de resolver, especialmente em uma folha de estilo grande.

+ +

Uma situação em que você pode ter que usá-lo é quando você está trabalhando em um CMS onde você não pode editar os módulos CSS principais e você realmente deseja sobrescrever um estilo que não pode ser sobrescrito de nenhuma outra maneira. Mas, sério, não use se você puder evitar.

+ +

O Efeito da Localização CSS

+ +

Por fim, também é útil observar que a importância de uma declaração CSS depende em qual folha de estilo ela é especificada - é possível que os usuários definam folhas de estilo personalizadas para substituir os estilos do desenvolvedor, por exemplo, o usuário pode ser deficiente visual e deseja para definir o tamanho da fonte em todas as páginas da Web que eles visitam com o dobro do tamanho normal para permitir uma leitura mais fácil.

+ +

Resumindo

+ +

As declarações conflitantes serão aplicadas na seguinte ordem, com as posteriores substituindo as anteriores:

+ +
    +
  1. Declarações nas folhas de estilo do agente do usuário (por exemplo, os estilos padrão do navegador, usados quando nenhum outro estilo está definido).
  2. +
  3. Declarações normais em folhas de estilo do usuário (estilos personalizados definidos por um usuário).
  4. +
  5. Declarações normais em folhas de estilo do autor (esses são os estilos definidos por nós, os desenvolvedores da web).
  6. +
  7. Declarações importantes nas folhas de estilo do autor
  8. +
  9. +

    Declarações importantes nas folhas de estilo do usuário

    + +

    Faz sentido que as folhas de estilo dos desenvolvedores da web substituam as folhas de estilo do usuário, para que o design possa ser mantido conforme pretendido, mas às vezes os usuários têm bons motivos para substituir os estilos do desenvolvedor da web, conforme mencionado acima - isso pode ser feito usando! Important em suas regras.
    +  

    +
  10. +
+ +

Teste suas Habilidades!

+ +

Abordamos muito neste artigo, mas você consegue se lembrar das informações mais importantes? Você pode encontrar mais alguns testes para verificar se reteve essas informações antes de prosseguir - consulte Test your skills: the Cascade.

+ +

O que vem a seguir?

+ +

Se você entendeu a maior parte deste artigo, então muito bem - você começou a se familiarizar com a mecânica fundamental do CSS. A seguir, veremos os seletores em detalhes.

+ +

Se você não entendeu totalmente a cascata, a especificidade e a herança, não se preocupe! Esta é definitivamente a coisa mais complicada que abordamos até agora no curso e é algo que até mesmo os desenvolvedores profissionais da Web às vezes acham complicado. Aconselhamos que você volte a este artigo algumas vezes à medida que avança no curso e continue pensando a respeito.

+ +

Volte aqui se você começar a encontrar problemas estranhos com estilos que não se aplicam conforme o esperado. Pode ser um problema de especificidade.

+ +

{{NextMenu("Learn/CSS/Building_blocks/Selectors", "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/index.html b/files/pt-br/learn/css/building_blocks/index.html new file mode 100644 index 0000000000..b79de8baa0 --- /dev/null +++ b/files/pt-br/learn/css/building_blocks/index.html @@ -0,0 +1,83 @@ +--- +title: Construindo blocos CSS +slug: Aprender/CSS/Construindo_blocos +translation_of: Learn/CSS/Building_blocks +--- +
{{LearnSidebar}}
+ +

Este módulo continua onde Primeiros passos em CSS parou — agora que você já ganhou familiaridade com a linguagem e sua sintaxe, e já tem alguma experiência básica usando-a, é hora de mergulhar um pouco mais fundo. Este módulo analisa a conceitos de cascata e herança , todos os tipos de seletores que temos disponíveis, unidades, dimensionamentos, estilos de fundo e bordas, depuração, e muito mais.

+ +

O objetivo aqui é lhe prover com um conjunto de ferramentas para construir um código CSS competente e ajuda-lo a entender toda a teoria essencial, antes de passarmos para tópicos mais específicos como Estilização de texto e Modelo CSS.

+ +

Pré-requisitos

+ +

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

+ +
    +
  1. Familiaridade básica com uso de computadores, e usar a Web passivamente (por exemplo. apenas olhar, 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, como detalhado em Lidando com arquivos.
  4. +
  5. Familiaridade básica com HTML, como foi discutido no módulo Introdução ao HTML.
  6. +
  7. Um entendimento do básico em CSS, como o mostrado no módulo  Primeiros Passos com CSS.
  8. +
+ +
+

Nota: Se você estiver usando um computador/tablet/outro dispositivo onde você não puder criar seus próprios arquivos, você pode tentar rodar (a maioria) os códigos de exemplo em um programa de codificação online como o JSBin ou Glitch.

+
+ +

Guias

+ +

Este módulo contém os seguintes artigos, que cobrem a maioria das partes essenciais da linguagem CSS. Ao longo do caminho você encontrará vários exercícios para testar seu entendimento.

+ +
+
Cascata e Herança
+
O objetivo desta lição é desenvolver seu entendimento de alguns dos conceitos mais fundamentais do CSS — a cascata, especificidade e herança — que controlam como o CSS será aplicado ao HTML e como conflitos são resolvidos.
+
Seletores CSS
+
Há uma ampla variedade de seletores CSS disponíveis, permitindo uma fina precisão ao selecionar elementos para estilizar. Neste artigo e em seus sub-artigos, examinaremos os diferentes tipos em detalhes, vendo como eles funcionam. Os sub-artigos são os seguintes: + +
+
O modelo de caixa (Ou Box Model)
+
Tudo em CSS está dentro de caixas, e entender essas caixas é a chave para estar apto a criar layouts (modelos) em CSS, ou alinhar itens com outros itens. Nesta lição,trataremos mais propriamente sobre Modelo de Caixa CSS, afim de que você possa passar para tarefas de Layout mais complexas com um entendimento de como isto funciona e a terminologia relacionada a este modelo.
+
Planos de fundo e bordas
+
Nesta lição, examinaremos algumas das coisas criativas que você pode fazer com os planos de fundo e as bordas do CSS. Desde a criação de gradientes, imagens de plano de fundo e cantos arredondados, planos de fundo e bordas são a resposta para muitas questões de estilo em CSS.
+
Manipulando diferentes direções de texto
+
Nos últimos anos, o CSS evoluiu para oferecer melhor suporte a diferentes direções de conteúdo, incluindo o conteúdo da direita para a esquerda, mas também de cima para baixo (como o japonês) - essas diferentes direções são chamadas de modos de escrita. À medida que você progride em seu estudo e começa a trabalhar com o layout, o entendimento dos modos de escrita será muito útil para você; portanto, os apresentaremos neste artigo..
+
Transbordando conteúdo
+
Nesta lição, examinaremos outro conceito importante em CSS - overflow, efeito de transbordar. O overflow é o que acontece quando há muito conteúdo para ser contido adequadamente dentro de uma "caixa". Neste guia, você aprenderá o que é e como gerenciá-lo.
+
Valores CSS e unidades
+
Cada propriedade usada em CSS tem um valor ou um conjunto de valores que são permitidos para uma dada propriedade, veremos alguns dos valores e unidades mais comuns em uso.
+
Dimensionando itens em CSS
+
Nas várias lições até agora, você encontrou várias maneiras de dimensionar itens em uma página da Web usando CSS. É importante entender o tamanho dos diferentes recursos do seu design e, nesta lição, resumiremos as várias maneiras pelas quais os elementos obtêm um tamanho via CSS e definiremos alguns termos de dimensionamento que ajudarão você no futuro.
+
Imagens, mídia, e elementos de formulário
+
Nesta lição, veremos como certos elementos especiais são tratados no CSS. Imagens, outras mídias e elementos de formulário se comportam de maneira um pouco diferente em termos de sua capacidade de estilizá-los com CSS do que as caixas regulares. Compreender o que é e o que não é possível pode poupa-lo de algumas frustrações, e esta lição destacará algumas das principais coisas que você precisa saber.
+
Estilizando Tabelas
+
Estilizar uma tabela HTML não é o trabalho mais fascinante do mundo, mas às vezes todos nós precisamos fazê-lo. Este artigo fornece um guia para melhorar a aparência das tabelas HTML, com algumas técnicas específicas de estilo de tabela destacadas.
+
Depurando CSS
+
Às vezes, ao escrever CSS, você encontrará um problema em que seu CSS parece não estar fazendo o que você espera. Este artigo fornecerá orientações sobre como depurar um problema de CSS e mostrará como os DevTools (ferramentas de desenvolvedor) incluídos em todos os navegadores modernos podem ajudá-lo a descobrir o que está acontecendo.
+
Organizando seu CSS
+
Ao começar a trabalhar com folhas de estilo e em projetos maiores, você descobrirá que manter um grande arquivo CSS pode ser desafiador. Neste artigo, examinaremos brevemente algumas práticas recomendadas para escrever seu CSS para facilitar a manutenção e algumas das soluções que você encontrará em uso por outras pessoas para ajudar a melhorar a capacidade de manutenção.
+
+ +

Avaliações

+ +

Deseja testar suas habilidades de CSS? As avaliações a seguir testarão sua compreensão do CSS abordado nos guias acima.

+ +
+
Entendimento fundamental de CSS
+
Esta avaliação testará seu entendimento da sintaxe básica, seletores, especificidade, modelo caixa, e mais.
+
Criando uma carta timbrada ideal
+
Se você deseja causar uma boa impressão, escrever uma carta em papel timbrado bonito pode ser um bom começo. Nesta avaliação, desafiaremos você a criar um modelo online para obter essa aparência.
+
Caixa de estilo atraente
+
Aqui você aprenderá a usar o estilo de plano de fundo e borda para criar uma caixa agradável.
+
+ +

Veja também

+ +
+
Efeitos de estilo avançados
+
Este artigo funciona como uma caixa de truques, fornecendo uma introdução a alguns recursos avançados de estilo interessantes, como sombras de caixa, modos de mesclagem e filtros.
+
diff --git a/files/pt-br/learn/css/building_blocks/the_box_model/index.html b/files/pt-br/learn/css/building_blocks/the_box_model/index.html new file mode 100644 index 0000000000..841540a8f0 --- /dev/null +++ b/files/pt-br/learn/css/building_blocks/the_box_model/index.html @@ -0,0 +1,343 @@ +--- +title: The box model +slug: Aprender/CSS/Construindo_blocos/The_box_model +translation_of: Learn/CSS/Building_blocks/The_box_model +--- +
{{LearnSidebar}}{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Combinators", "Learn/CSS/Building_blocks/Backgrounds_and_borders", "Learn/CSS/Building_blocks")}}
+ +

Tudo em CSS tem um quadro em torno de si, e entender estes quadros é chave para ser capaz de criar arranjos ( layouts ) com CSS, ou para alinhar itens com outros itens. Nesta lição, olharemos de modo apropiado para o modelo de caixas do CSS ( CSS Box Model ), de forma que você possa montar arranjos mais complexos com um melhor entendimento de como ele funciona e da terminologia relacionada.

+ + + + + + + + + + + + +
Pré-requisitos:Familiaridade básica em utilizar computadores, ambiente de trabalho básico configurado conforme detalhado emsoftware básico instalado, conhecimento básico de como criar e gerenciar arquivos, básico de HTML ( Introdução ao HTML), e uma idéia de como o  CSS funciona (ensinado em CSS primeiros passos.)
Objetivo:Aprender sobre o Modelo de Caixa do CSS, o que faz o modelo de caixa e como trocar para um modelo alternativo.
+ +

Block and inline boxes

+ +

In CSS we broadly have two types of boxes — block boxes and inline boxes. These characteristics refer to how the box behaves in terms of page flow, and in relation to other boxes on the page:

+ +

If a box is defined as a block, it will behave in the following ways:

+ + + +

Unless we decide to change the display type to inline, elements such as headings (e.g. <h1>) and <p> all use block as their outer display type by default.

+ +

If a box has an outer display type of inline, then:

+ + + +

The <a> element, used for links, <span>, <em> and <strong> are all examples of elements that will display inline by default.

+ +

The type of box applied to an element is defined by {{cssxref("display")}} property values such as block and inline, and relates to the outer value of display.

+ +

Além disto: Tipos de exibição ( display ) internos e externos

+ +

Nesse ponto, é melhor também explicar os tipos de exibição interna ( inner ) e externa ( outer ). Como mencionado acima, as caixas em CSS têm um tipo de exibição externa, que detalha se a caixa é em bloco ou em linha.

+ +

Caixas possuem também um tipo de display inner, que determina como elementos dentro da caixa são posicionados. Por default, os elementos dentro de uma caixa são posicionados em um fluxo normal ( normal flow ), significando que eles se comportam como qualquer outro bloco e elementos inline (como explicado acima).

+ +

We can, however, change the inner display type by using display values like flex. If we set display: flex; on an element, the outer display type is block, but the inner display type is changed to flex. Any direct children of this box will become flex items and will be laid out according to the rules set out in the Flexbox spec, which you'll learn about later on.

+ +
+

Note: To read more about the values of display, and how boxes work in block and inline layout, take a look at the MDN guide to Block and Inline Layout.

+
+ +

When you move on to learn about CSS Layout in more detail, you will encounter flex, and various other inner values that your boxes can have, for example grid.

+ +

Block and inline layout, however, is the default way that things on the web behave — as we said above, it is sometimes referred to as normal flow, because without any other instruction, our boxes lay out as block or inline boxes.

+ +

Examples of different display types

+ +

Let's move on and have a look at some examples. Below we have three different HTML elements, all of which have an outer display type of block. The first is a paragraph, which has a border added in CSS. The browser renders this as a block box, so the paragraph begins on a new line, and expands to the full width available to it.

+ +

The second is a list, which is laid out using display: flex. This establishes flex layout for the items inside the container, however, the list itself is a block box and — like the paragraph — expands to the full container width and breaks onto a new line.

+ +

Below this, we have a block-level paragraph, inside which are two <span> elements. These elements would normally be inline, however, one of the elements has a class of block, and we have set it to display: block.

+ +

{{EmbedGHLiveSample("css-examples/learn/box-model/block.html", '100%', 1000)}} 

+ +

We can see how inline elements behave in this next example. The <span> elements in the first paragraph are inline by default and so do not force line breaks.

+ +

We also have a <ul> element which is set to display: inline-flex, creating an inline box around some flex items.

+ +

Finally, we have two paragraphs both set to display: inline. The inline flex container and paragraphs all run together on one line rather than breaking onto new lines as they would do if they were displaying as block-level elements.

+ +

In the example, you can change display: inline to display: block or display: inline-flex to display: flex to toggle between these display modes.

+ +

{{EmbedGHLiveSample("css-examples/learn/box-model/inline.html", '100%', 1000)}} 

+ +

You will encounter things like flex layout later in these lessons; the key thing to remember for now is that changing the value of the display property can change whether the outer display type of a box is block or inline, which changes the way it displays alongside other elements in the layout. 

+ +

In the rest of the lesson, we will concentrate on the outer display type.

+ +

What is the CSS box model?

+ +

The full CSS box model applies to block boxes, inline boxes only use some of the behavior defined in the box model. The model defines how the different parts of a box — margin, border, padding, and content — work together to create a box that you can see on the page. To add some additional complexity, there is a standard and an alternate box model.

+ +

Parts of a box

+ +

Making up a block box in CSS we have the:

+ + + +

The below diagram shows these layers:

+ +

Diagram of the box model

+ +

The standard CSS box model

+ +

In the standard box model, if you give a box a width and a height attribute, this defines the width and height of the content box. Any padding and border is then added to that width and height to get the total size taken up by the box. This is shown in the image below.

+ +

If we assume that the box has the following CSS defining width, height, margin, border, and padding:

+ +
.box {
+  width: 350px;
+  height: 150px;
+  margin: 10px;
+  padding: 25px;
+  border: 5px solid black;
+}
+
+ +

The space taken up by our box using the standard box model will actually be 410px (350 + 25 + 25 + 5 + 5), and the height 210px (150 + 25 + 25 + 5 + 5), as the padding and border are added to the width used for the content box.

+ +

Showing the size of the box when the standard box model is being used.

+ +
+

Note: The margin is not counted towards the actual size of the box — sure, it affects the total space that the box will take up on the page, but only the space outside the box. The box's area stops at the border — it does not extend into the margin.

+
+ +

The alternative CSS box model

+ +

You might think it is rather inconvenient to have to add up the border and padding to get the real size of the box, and you would be right! For this reason, CSS had an alternative box model introduced some time after the standard box model. Using this model, any width is the width of the visible box on the page, therefore the content area width is that width minus the width for the padding and border. The same CSS as used above would give the below result (width = 350px, height = 150px).

+ +

Showing the size of the box when the alternate box model is being used.

+ +

By default, browsers use the standard box model. If you want to turn on the alternative model for an element you do so by setting box-sizing: border-box on it. By doing this you are telling the browser to take the border box as the area defined by any size you set.

+ +
.box {
+  box-sizing: border-box;
+} 
+ +

If you want all of your elements to use the alternative box model, and this is a common choice among developers, set the box-sizing property on the <html> element, then set all other elements to inherit that value, as seen in the snippet below. If you want to understand the thinking behind this, see the CSS Tricks article on box-sizing.

+ +
html {
+  box-sizing: border-box;
+}
+*, *::before, *::after {
+  box-sizing: inherit;
+}
+ +
+

Note: An interesting bit of history — Internet Explorer used to default to the alternative box model, with no mechanism available to switch.

+
+ +

Playing with box models

+ +

In the below example, you can see two boxes. Both have a class of .box, which gives them the same width, height, margin, border, and padding. The only difference is that the second box has been set to use the alternative box model.

+ +

Can you change the size of the second box (by adding CSS to the .alternate class) to make it match the first box in width and height?

+ +

{{EmbedGHLiveSample("css-examples/learn/box-model/box-models.html", '100%', 1000)}} 

+ +
+

Note: You can find a solution for this task here.

+
+ +

Use browser DevTools to view the box model

+ +

Your browser developer tools can make understanding the box model far easier. If you inspect an element in Firefox's DevTools, you can see the size of the element plus its margin, padding, and border. Inspecting an element in this way is a great way to find out if your box is really the size you think it is!

+ +

Inspecting the box model of an element using Firefox DevTools

+ +

Margins, padding, and borders

+ +

You've already seen the {{cssxref("margin")}}, {{cssxref("padding")}}, and {{cssxref("border")}} properties at work in the example above. The properties used in that example are shorthands and allow us to set all four sides of the box at once. These shorthands also have equivalent longhand properties, which allow control over the different sides of the box individually.

+ +

Let's explore these properties in more detail.

+ +

Margin

+ +

The margin is an invisible space around your box. It pushes other elements away from the box. Margins can have positive or negative values. Setting a negative margin on one side of your box can cause it to overlap other things on the page. Whether you are using the standard or alternative box model, the margin is always added after the size of the visible box has been calculated.

+ +

We can control all margins of an element at once using the {{cssxref("margin")}} property, or each side individually using the equivalent longhand properties:

+ + + +

In the example below, try changing the margin values to see how the box is pushed around due to the margin creating or removing space (if it is a negative margin) between this element and the containing element.

+ +

{{EmbedGHLiveSample("css-examples/learn/box-model/margin.html", '100%', 1000)}} 

+ +

Margin collapsing

+ +

A key thing to understand about margins is the concept of margin collapsing. If you have two elements whose margins touch, and both margins are positive, those margins will combine to become one margin, which is the size of the largest individual margin. If one or both margins are negative, the amount of negative value will subtract from the total.

+ +

In the example below, we have two paragraphs. The top paragraph has a margin-bottom of 50 pixels. The second paragraph has a margin-top of 30 pixels. The margins have collapsed together so the actual margin between the boxes is 50 pixels and not the total of the two margins.

+ +

You can test this by setting the margin-top of paragraph two to 0. The visible margin between the two paragraphs will not change — it retains the 50 pixels set in the bottom-margin of paragraph one. If you set it to -10px, you'll see that the overall margin becomes 40px — it subtracts from the 50px.

+ +

{{EmbedGHLiveSample("css-examples/learn/box-model/margin-collapse.html", '100%', 1000)}} 

+ +

There are a number of rules that dictate when margins do and do not collapse. For further information see the detailed page on mastering margin collapsing. The main thing to remember for now is that margin collapsing is a thing that happens. If you are creating space with margins and don't get the space you expect, this is probably what is happening.

+ +

Borders

+ +

The border is drawn between the margin and the padding of a box. If you are using the standard box model, the size of the border is added to the width and height of the box. If you are using the alternative box model then the size of the border makes the content box smaller as it takes up some of that available width and height.

+ +

For styling borders, there are a large number of properties — there are four borders, and each border has a style, width and color that we might want to manipulate.

+ +

You can set the width, style, or color of all four borders at once using the {{cssxref("border")}} property.

+ +

To set the properties of each side individually, you can use:

+ + + +

To set the width, style, or color of all sides, use the following:

+ + + +

To set the width, style, or color of a single side, you can use one of the most granular longhand properties:

+ + + +

In the example below we have used various shorthands and longhands to create borders. Have a play around with the different properties to check that you understand how they work. The MDN pages for the border properties give you information about the different styles of border you can choose from.

+ +

{{EmbedGHLiveSample("css-examples/learn/box-model/border.html", '100%', 1000)}} 

+ +

Padding

+ +

The padding sits between the border and the content area. Unlike margins you cannot have negative amounts of padding, so the value must be 0 or a positive value. Any background applied to your element will display behind the padding, and it is typically used to push the content away from the border.

+ +

We can control the padding on each side of an element individually using the {{cssxref("padding")}} property, or each side individually using the equivalent longhand properties:

+ + + +

If you change the values for padding on the class .box in the example below you can see that this changes where the text begins in relation to the box.

+ +

You can also change the padding on the class .container, which will make space between the container and the box. Padding can be changed on any element, and will make space between its border and whatever is inside the element.

+ +

{{EmbedGHLiveSample("css-examples/learn/box-model/padding.html", '100%', 800)}} 

+ +

The box model and inline boxes

+ +

All of the above applies fully to block boxes. Some of the properties can apply to inline boxes too, such as those created by a <span> element.

+ +

In the example below, we have a <span> inside a paragraph and have applied a width, height, margin, border, and padding to it. You can see that the width and height are ignored. The vertical margin, padding, and border are respected but they do not change the relationship of other content to our inline box and so the padding and border overlaps other words in the paragraph. Horizontal padding, margins, and borders are respected and will cause other content to move away from the box.

+ +

{{EmbedGHLiveSample("css-examples/learn/box-model/inline-box-model.html", '100%', 800)}} 

+ +

Using display: inline-block

+ +

There is a special value of display, which provides a middle ground between inline and block. This is useful for situations where you do not want an item to break onto a new line, but do want it to respect width and height and avoid the overlapping seen above.

+ +

An element with display: inline-block does a subset of the block things we already know about:

+ + + +

It does not, however, break onto a new line, and will only become larger than its content if you explicitly add width and height properties.

+ +

In this next example, we have added display: inline-block to our <span> element. Try changing this to display: block or removing the line completely to see the difference in display models.

+ +

{{EmbedGHLiveSample("css-examples/learn/box-model/inline-block.html", '100%', 800)}} 

+ +

Where this can be useful is when you want to give a link to a larger hit area by adding padding. <a> is an inline element like <span>; you can use display: inline-block to allow padding to be set on it, making it easier for a user to click the link.

+ +

You see this fairly frequently in navigation bars. The navigation below is displayed in a row using flexbox and we have added padding to the <a> element as we want to be able to change the background-color when the <a> is hovered. The padding appears to overlap the border on the <ul> element. This is because the <a> is an inline element.

+ +

Add display: inline-block to the rule with the .links-list a selector, and you will see how it fixes this issue by causing the padding to be respected by other elements.

+ +

{{EmbedGHLiveSample("css-examples/learn/box-model/inline-block-nav.html", '100%', 600)}} 

+ +

Test your skills!

+ +

We have covered a lot in this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: The Box Model.

+ +

Summary

+ +

That's most of what you need to understand about the box model. You may want to return to this lesson in the future if you ever find yourself confused about how big boxes are in your layout.

+ +

In the next lesson, we will take a look at how backgrounds and borders can be used to make your plain boxes look more interesting.

+ +

{{PreviousMenuNext("Learn/CSS/Building_blocks/Selectors/Combinators", "Learn/CSS/Building_blocks/Backgrounds_and_borders", "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/css_layout/fluxo_normal/index.html b/files/pt-br/learn/css/css_layout/fluxo_normal/index.html deleted file mode 100644 index c27a403fa7..0000000000 --- a/files/pt-br/learn/css/css_layout/fluxo_normal/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -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/intro_leiaute_css/index.html b/files/pt-br/learn/css/css_layout/intro_leiaute_css/index.html deleted file mode 100644 index 9314e8efd3..0000000000 --- a/files/pt-br/learn/css/css_layout/intro_leiaute_css/index.html +++ /dev/null @@ -1,707 +0,0 @@ ---- -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/introduction/index.html b/files/pt-br/learn/css/css_layout/introduction/index.html new file mode 100644 index 0000000000..9314e8efd3 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/introduction/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 deleted file mode 100644 index 2605843ff4..0000000000 --- a/files/pt-br/learn/css/css_layout/layout_de_varias_colunas/index.html +++ /dev/null @@ -1,414 +0,0 @@ ---- -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/multiple-column_layout/index.html b/files/pt-br/learn/css/css_layout/multiple-column_layout/index.html new file mode 100644 index 0000000000..2605843ff4 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/multiple-column_layout/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/normal_flow/index.html b/files/pt-br/learn/css/css_layout/normal_flow/index.html new file mode 100644 index 0000000000..c27a403fa7 --- /dev/null +++ b/files/pt-br/learn/css/css_layout/normal_flow/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/first_steps/como_css_e_estruturado/index.html b/files/pt-br/learn/css/first_steps/como_css_e_estruturado/index.html deleted file mode 100644 index 4084647920..0000000000 --- a/files/pt-br/learn/css/first_steps/como_css_e_estruturado/index.html +++ /dev/null @@ -1,502 +0,0 @@ ---- -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/getting_started/index.html b/files/pt-br/learn/css/first_steps/getting_started/index.html new file mode 100644 index 0000000000..a9a5218e98 --- /dev/null +++ b/files/pt-br/learn/css/first_steps/getting_started/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/how_css_is_structured/index.html b/files/pt-br/learn/css/first_steps/how_css_is_structured/index.html new file mode 100644 index 0000000000..4084647920 --- /dev/null +++ b/files/pt-br/learn/css/first_steps/how_css_is_structured/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/iniciando/index.html b/files/pt-br/learn/css/first_steps/iniciando/index.html deleted file mode 100644 index a9a5218e98..0000000000 --- a/files/pt-br/learn/css/first_steps/iniciando/index.html +++ /dev/null @@ -1,265 +0,0 @@ ---- -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 deleted file mode 100644 index 41980dfee6..0000000000 --- a/files/pt-br/learn/css/first_steps/o_que_e_css/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -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/what_is_css/index.html b/files/pt-br/learn/css/first_steps/what_is_css/index.html new file mode 100644 index 0000000000..41980dfee6 --- /dev/null +++ b/files/pt-br/learn/css/first_steps/what_is_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/howto/css_faq/index.html b/files/pt-br/learn/css/howto/css_faq/index.html new file mode 100644 index 0000000000..f3febd4637 --- /dev/null +++ b/files/pt-br/learn/css/howto/css_faq/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/css_perguntas_frequentes/index.html b/files/pt-br/learn/css/howto/css_perguntas_frequentes/index.html deleted file mode 100644 index f3febd4637..0000000000 --- a/files/pt-br/learn/css/howto/css_perguntas_frequentes/index.html +++ /dev/null @@ -1,245 +0,0 @@ ---- -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/index.html b/files/pt-br/learn/css/index.html new file mode 100644 index 0000000000..f5004d47f3 --- /dev/null +++ b/files/pt-br/learn/css/index.html @@ -0,0 +1,61 @@ +--- +title: Aprenda a estilizar HTML utilizando CSS +slug: Aprender/CSS +tags: + - CSS + - Folha de Estilos + - Iniciante + - especificação +translation_of: Learn/CSS +--- +

Cascading Stylesheets — ou {{glossary("CSS")}} — é a primeira tecnologia que você deve aprender após o {{glossary("HTML")}}. Enquanto o HTML é utilizado para definir a estrutura e semântica do seu conteúdo, o CSS é usado para estilizá-lo e desenhá-lo. Por exemplo, você pode usar o CSS para alterar a fonte, cor, tamanho e espaçamento do seu conteúdo, dividí-lo em multiplas colunas, ou adicionar animações e outros recursos decorativos.

+ +

Percurso de aprendizagem

+ +

Você deveria aprender o básico de HTML antes de tentar algo com CSS. Nós recomendamos que você comece através da nossa Introdução ao HTML.Neste módulo você irá aprender sobre:

+ + + +

Uma vez que voce entendeu os Fundamentos do HTML, Nós recomendamos que você aprenda HTML e CSS ao mesmo tempo, movendo-se para trás e para frente entre os dois temas. Isso por que HTML é muito mais interessante com CSS e você não pode aprender realmente CSS sem conhecer HTML.

+ +

Antes de iniciar este tópico, você também deve ter ao menos familiaridade com o uso de computadores, e utilizar a Web passivamente (isto é, apenas navegando e consumindo conteúdo.) Você deve ter uma configuração básica de ambiente de trabalho, conforme detalhado no Instalando o software básico, e entender como criar e gerenciar arquivos, conforme detalhado em Lidando com arquivos — ambos são partes do nosso Como começar com a web módulo completo de iniciante.

+ +

É recomendável que você trabalhe através do Como começar com a web antes de começar este tema. Contudo, não é absolutamente necessário; ja que muito do que é abordado no artigo básico de CSS também é coberto em nossa introdução ao CSS, embora com muito mais detalhes.

+ +

Módulos

+ +

Este tópico contém os seguintes módulos em uma ordem sugerida para trabalhar através deles. Você deve definitivamente começar com o primeiro.

+ +
+
Introdução ao CSS
+
Este módulo é uma introdução com as noções básicas de como CSS funciona, incluindo seletores e propriedades, escrever regras CSS, aplicando CSS para HTML, como especificar comprimento, cor e outras unidades em CSS, controlar cascatas e heranças, noções básicas de box model e depuração CSS.
+
Estilo de texto
+
Aqui nós olhamos os fundamentos do estilos de texto, incluindo a configuração da fonte, negrito, itálico, linha e espaçamento das letras, além de sombras e outros componentes de texto. Nós usamos este módulo para personalizar fontes para sua página, e estilizar listas e links.
+
Caixas de estilo
+
Próximo, procuramos as caixas de estilo, um dos passos fundamentais para elaborar uma página web. Neste módulo, nós recapitulamos box model para então controlarmos o layout por configuração de padding, borders e margins, configurações personalizada do background colors , imagens e outros componentes, componentes elegantes tais como sombras e filtros das caixas.
+
CSS layout
+
Neste ponto, nós olharemos os fundamentos CSS, como estilizar o texto, e como estilizar e manipular as caixas com conteudos alocados. Agora é hora de olhar como pôr suas caixas no lugar certo em relação ao viewport,  e outros. Nós temos cobertos os pré-requisitos necessários para então agora podemos aprofundar no layout CSS, olhar em diferentes configurações de telas, tradicionais métodos envolvendo float e posicionamento, além de novos ferramentas de flanged layouts como flexbox, CSS Grid e posicionamento, alem de algumas tecnicas que voce ainda pode querer conhecer.
+
Design Responsivo (TBD)
+
Com tantos tipos diferentes de dispositivos capazes de navegar pela internet nos dias de hoje, design web responsivo (RWD) se tornou uma habilidade primordial para o desenvolvimento web. Esse módulo irá cobrir os principios básicos e ferramentas do RWD, explicar como aplicar diferentes arquivos CSS à um documento a depender de dos recursos do dispositivo como largura de tela, orientação, e resolução, e explorar tecnologias disponíveis para servir diferentes vídeos e imagens dependendo de tais recursos.
+
Animações e transformações (TBD)
+
Duas das áreas mais interessantes do CSS são a habilidade de manipular elementos (ex. mover, rotacionar e inclinação), e animar elementos suavemente (ex. de uma cor ou posição para outra). Esse módulo explora como implementar as transformações e animações.
+
+ +

Resolvendo problemas de CSS comuns

+ +

Use CSS para resolver problemas comuns proporcione links para seções de conteúdo explicando como usar CSS para resolver problemas muito comuns na criação de páginas web.

+ +

Para começar, primeirmamente você aplicara cores aos elementos HTML e seus backgrounds;  alterará o tamanho, forma e posição dos elementos; definira e adicionara bordas aos elementos. Não há muito o que você não podera fazer depois que tiver uma compreensão solida até mesmo sobre o basico do CSS. Uma das melhores coisas sobre aprender CSS é que uma vez que voce conhece os fundamentos, normalmente voce tera uma boa noção do que pode ou não fazer, mesmo que não saiba como fazer aquilo ainda.

+ +

Veja também

+ +
+
CSS no MDN
+
O principal ponto de entrada para documentação CSS no MDN, onde voce encontra desde referências detalhadas a tutoriais avançados. Quer saber todos os valores que uma propriedade pode ter? Este é o melhor lugar
+
Referência CSS
+
Um guia de referência abrangente para todos os muitos recursos da linguagem CSS - se você quiser saber quais valores uma propriedade pode tomar, por exemplo, este é um ótimo lugar para começar.
+
diff --git a/files/pt-br/learn/css/styling_text/index.html b/files/pt-br/learn/css/styling_text/index.html new file mode 100644 index 0000000000..b2eafa9f05 --- /dev/null +++ b/files/pt-br/learn/css/styling_text/index.html @@ -0,0 +1,48 @@ +--- +title: Estilizando texto +slug: Aprender/CSS/Estilizando_texto +tags: + - CSS + - Fontes + - Iniciante + - Links + - Texto + - listas + - web fontes +translation_of: Learn/CSS/Styling_text +--- +
{{LearnSidebar}}
+ +

Com o básico de CSS compreendido, o próximo passo para você se concentrar será a estilização de textos — uma das mais importantes coisas que você fará com CSS. Aqui nós olhamos para os fundamentos de estilização de texto, fontes, negritos, italicos, linha e espaço entre letras, sombreamente e outras características textuais. Completamos o módulo produrando aplicar fontes personalizadas para sua página, e estilizando listas e links.

+ +

Pré-requisites

+ +

Antes de começar este módulo, você já deverá ter familiaridade básica com HTML, como dissemos no módulos Introdução ao HTML, e estar confortável com os fundamentos de CSS, como discutido em Introdução ao CSS.

+ +
+

Nota: Se você está usando um computador/tablet/outro dispositivo onde não tem a possibilidade de criar seus próprios arquivos, você poderá treinar os códigos-exemplo em um programa de código online como JSBin, CodePen or Thimble.

+
+ +

Guias

+ +

Este módulo contém os seguintes artigos que ensinarão você todos os fundamentos por trás da estilização de conteúdo textual HTML.

+ +
+
Fundamentos da estilização de texto e fontes
+
Neste artigo nós passamos por todo o básico da estilização de texto/fonte, incluindo a configuração weight(negrito), family e style, configuração com forma abreviada, alinhamento textual, linha e espaçamento entre as letras.
+
Estilizando lista
+
Listas comportam-se como qualquer texto na maior parte das vezes, ma há algumas propriedades CSS específicas para lista que você precisa conhecer, e algumas boas práticas a considerar. Este artigo esclarecerá tudo.
+
Estilizando links
+
Na estilização de links, é importante entender como fazer uso de pseudo-classes para estilizar o estado dos links efetivamente, como estilizar links para uso em recursos de interfaces diversas como menus de navegação e guias. Veremos todos esses tópicos neste artigo.
+
Web Fontes
+
Aqui nós exploraremos Web Fontes em detalhes — isto permite que você baixe fontes personalizadas junto com sua página web, para permitir maior personalização na estilização.
+
+ +

Avaliação

+ +

A seguinte avaliação testará seu entendimento das técnicas de estilização de texto cobertas pelo guia acima.

+ +
+
Estilizando a homepage de um escola comunitária
+
Nesta avaliação nos testeremos seu entendimento de estilização de texto fazendo com que você estilize a homepage de uma escola comunitária.
+
diff --git a/files/pt-br/learn/css/styling_text/styling_lists/index.html b/files/pt-br/learn/css/styling_text/styling_lists/index.html new file mode 100644 index 0000000000..72dc8dc227 --- /dev/null +++ b/files/pt-br/learn/css/styling_text/styling_lists/index.html @@ -0,0 +1,272 @@ +--- +title: Manipulando Listas +slug: Web/CSS/Getting_Started/Lists +translation_of: Learn/CSS/Styling_text/Styling_lists +translation_of_original: Web/Guide/CSS/Getting_started/Lists +--- +

{{ CSSTutorialTOC() }}

+ +

{{ previousPage("/en-US/docs/Web/Guide/CSS/Getting_Started/Content", "Content") }}

+ +

Este é o 10º seção do CSS Introdução tutorial; ele descreve como você pode usar CSS para especificar o aparecimento de listas. Você cria um novo documento de amostra contendo listas, e um novo estilo que os estilos das listas.

+ +

Informação: Lists

+ +

Se você aceitou o desafio na última seção, em seguida, você viu como você pode adicionar conteúdo antes de qualquer elemento para exibi-lo como um item da lista.

+ +

CSS proporciona propriedades especiais que são projetados para listas. Geralmente é mais conveniente usar estas propriedades sempre que puder.

+ +

Para especificar o estilo para uma lista, use o {{cssxref ("list-style")}} propriedade para especificar o tipo de marcador.

+ +

O seletor na sua regra de CSS pode selecionar os elementos de item de lista (por exemplo, {{HTMLElement ("li")}}), ou pode selecionar o elemento primário da lista (por exemplo, {{HTMLElement ("ul")}}) de modo a que os elementos da lista herdam o modelo.

+ +

Listas não ordenadas

+ +

Em uma lista desordenada, cada item da lista é marcado da mesma forma.

+ +

CSS tem três tipos de marcadores, e aqui está como seu navegador exibe-os:

+ + + +

        none

+ +

Alternativamente, você pode especificar o URL de uma imagem.

+ +
+
Exemplo
+ +

Essas regras especificam diferentes marcadores para diferentes classes de item da lista:

+ +
li.open {list-style: circle;} 
+li.closed {list-style: disc;}
+
+ +

Quando estas classes são usadas em uma lista, que distinguir entre os itens abertos e fechados (por exemplo, em uma lista de tarefas):

+ +
<ul> 
+  <li class="open"> Lorem ipsum </ li> 
+  <li class="closed"> dolor sit </ li>
+  <li class="closed"> Amet consectetuer </ li>
+  <li class="open"> Magna aliquam </ li>
+  <li class="closed"> Autem veleum </ li>
+</ ul>
+
+ +

O resultado pode parecer:

+ +

{{EmbedLiveSample ('Listas_não_ordenadas', '', '', '')}}

+
+ +

Listas ordenadas

+ +

Em uma listaordenada , cada item da lista é marcado diferentemente para mostrar a sua posição na sequência.

+ +

Use a propriedade {{cssxref ("list-style")}} para especificar o tipo de marcador:

+ + + +
+
Exemplo
+ +

Esta regra especifica que em {{HTMLElement ("OL")}} elementos com a classe informações, os itens são identificados com letras maiúsculas.

+ +
<ol class="info">
+  <li>Lorem ipsum</li>
+  <li>Dolor sit</li>
+  <li>Amet consectetuer</li>
+  <li>Magna aliquam</li>
+  <li>Autem veleum</li>
+</ol>
+ +
ol.info {list-style: upper-latin;}
+
+ +

O {{HTMLElement ("LI")}} elementos da lista herdam esse estilo:

+ +

{{EmbedLiveSample ('Listas_ordenadas', '', '', '')}}

+
+ +
+
Mais detalhes
+ +

O {{cssxref ("list-style")}} propriedade é uma propriedade taquigrafia. Em folhas de estilo complexas você pode preferir usar propriedades separadas para definir valores separados. Para obter links para essas propriedades separadas, e mais detalhes de como CSS especifica listas, consulte o {{cssxref ("list-style")}} página de referência.

+ +

Se você estiver usando uma linguagem de marcação como HTML que fornece etiquetas convencionais para não-ordenada ({{HTMLElement ("ul")}}) e ordenou ({{HTMLElement ("ol")}}) listas, então é uma boa prática para usar as marcas na forma como eles se destinam. No entanto, você pode usar CSS para fazer {{HTMLElement ("ul")}} exibição ordenada e {{HTMLElement ("ol")}} visualização não ordenada, se desejar.

+ +

Browsers diferem na maneira de implementar os estilos para listas. Não espere que sua folha de estilo dê resultados idênticos em todos os navegadores.

+
+ +

Contadores

+ +
+

Nota:  Alguns navegadores não suportam contadores. O conteúdo CSS e compatibilidade do navegador página no site de modo Quirks contém um gráfico detalhado de compatibilidade do navegador para este e outros recursos CSS. Páginas individuais na referência CSS neste local também têm tabelas de compatibilidade do navegador.

+
+ +

Você pode usar contadores para numerar quaisquer elementos, não somente itens da lista. Por exemplo, em alguns documentos você pode querer numerar cabeçalhos ou parágrafos.

+ +

Para especificar a numeração, você precisa de um contador com um nome que você especificar.

+ +

Em alguns elementos antes da contagem é começar, reinicie o contador com a propriedade {{cssxref ("counter-reset")}} eo nome do seu contador. O pai dos elementos que você estiver contando é um bom lugar para fazer isso, mas você pode usar qualquer elemento que vem antes os itens da lista.

+ +

Em cada elemento que o contador é incrementado, use a propriedade {{cssxref ("contra-incremento")}} eo nome do seu contador.

+ +

Para mostrar seu contador, adicione {{cssxref (":: before")}} ou {{cssxref (":: after")}} para o selector e usar o conteúdo da propriedade (como você fez na página anterior, Conteúdo) .

+ +

No valor do conteúdo de propriedade, especifique counter () com o nome de seu contador. Opcionalmente especifique um tipo. Os tipos são os mesmos que na lista ordenada secção acima.

+ +

Normalmente, o elemento que apresenta o contador também incrementa-lo.

+ +
+
Exemplo
+ +

Esta regra inicializa um contador para cada {{HTMLElement ("h3")}} elemento com a classe numeradas:

+ +
h3.numbered {counter-reset: mynum;}
+
+ +

 

+ +

Esta regra mostra e incrementa o contador para cada {{HTMLElement ("p")}} elemento com a classe numeradas:

+ +
<p class = "numbered"> Lorem ipsum </ p>
+<p class = "numbered"> dolor sit </ p>
+<p class = "numbered"> Amet consectetuer </ p>
+<p class = "numbered"> Magna aliquam </ p>
+<p class = "numbered"> Autem veleum </ p>
+
+ +
body 
+   {counter-reset: 
+mynum;} 
+p.numbered:before
+  {content: counter(mynum) ": ";
+  counter-increment: mynum;
+  font-weight: bold;}
+
+ +

O resultado se parece com isso:

+ +

{{ EmbedLiveSample("Contadores", '300', '200', '') }}

+
+ +
+
Mais detalhes
+ +

Você não pode usar os contadores a menos que você sabe que todo mundo que lê o documento tem um navegador que os suporta.

+ +

Se você é capaz de usar contadores, eles têm a vantagem de que você pode estilizar os contadores separadamente dos itens da lista. No exemplo acima, os contadores estão em negrito mas os itens da lista não são.

+ +

Você também pode usar contadores em formas mais complexas, por exemplo, para numerar seções, títulos, subtítulos e parágrafos em documentos formais. Para mais detalhes, consulte contadores automáticos e numeração em CSS Specification.

+
+ +

Listas denominadas: Ação

+ +

Crie um novo documento HTML, doc2.html. Copie e cole o conteúdo daqui:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="UTF-8">
+    <title>Sample document 2</title>
+    <link rel="stylesheet" href="style2.css">
+  </head>
+  <body>
+
+    <h3 id="oceans">The oceans</h3>
+    <ul>
+      <li>Arctic</li>
+      <li>Atlantic</li>
+      <li>Pacific</li>
+      <li>Indian</li>
+      <li>Southern</li>
+    </ul>
+
+    <h3 class="numbered">Numbered paragraphs</h3>
+    <p class="numbered">Lorem ipsum</p>
+    <p class="numbered">Dolor sit</p>
+    <p class="numbered">Amet consectetuer</p>
+    <p class="numbered">Magna aliquam</p>
+    <p class="numbered">Autem veleum</p>
+
+  </body>
+</html>
+
+
+ +

Faça uma nova folha de estilo, style2.css. Copie e cole o conteúdo daqui:

+ +
/* numbered paragraphs */
+h3.numbered {counter-reset: mynum;}
+
+p.numbered:before {
+  content: counter(mynum) ": ";
+  counter-increment: mynum;
+  font-weight: bold;
+}
+
+ +

Se o layout e comentário não são a seu gosto, alterá-los.

+ +

Abra o documento no seu browser. Se o seu navegador suporta contadores, você verá algo parecido com o exemplo abaixo. Se seu navegador não suporta contadores, então você não ver os números (e provavelmente nem mesmo os dois pontos):

+ +

{{EmbedLiveSample ('Listas_denominadas_Ação', '300', '400', '')}}

+ +
+
Desafios
+ +

Adicione uma regra à sua folha de estilo, para numerar os oceanos usando numerais romanos de I a V:

+ + + + + + + +
+

The oceans

+ +
    +
  • Arctic
  • +
  • Atlantic
  • +
  • Pacific
  • +
  • Indian
  • +
  • Southern
  • +
+
+ +

 

+ +

Mude sua folha de estilo para identificar os títulos com letras maiúsculas em parênteses como este:

+ + + + + + + +
+

(A) The oceans

+ +

. . .

+ +

(B) Numbered paragraphs

+ +

. . .

+
+
+ +

Ver soluções para esses desafios.

+ +

Qual o proximo?

+ +

{{NextPage ("/ en-US / docs / Web / Guia / CSS / Getting_Started / Boxes", "caixas")}} Quando seu navegador exibe seu documento de amostra, ele cria espaço ao redor dos elementos quando ele coloca-los na página. A próxima página descreve como você pode usar CSS para trabalhar com as formas subjacentes de elementos, caixas.

-- cgit v1.2.3-54-g00ecf