From 2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:50:24 +0100 Subject: unslug pt-pt: move --- files/pt-pt/learn/accessibility/index.html | 86 +++ files/pt-pt/learn/acessibilidade/index.html | 86 --- .../a_web_e_os_padroes_da_web/index.html | 174 ------ .../apresentacao_do_meu_site/index.html | 112 ---- .../como_funciona_a_web/index.html | 112 ---- .../learn/comecar_com_a_web/css_basico/index.html | 293 --------- .../elementar_de_javascript/index.html | 413 ------------ .../comecar_com_a_web/html_basicos/index.html | 237 ------- files/pt-pt/learn/comecar_com_a_web/index.html | 65 -- .../installing_basic_software/index.html | 165 ----- .../lidar_com_ficheiros/index.html | 119 ---- .../publicar_o_seu_site_da_web/index.html | 125 ---- .../how_does_the_internet_work/index.html | 100 +++ files/pt-pt/learn/common_questions/index.html | 131 ++++ .../index.html | 122 ++++ .../set_up_a_local_testing_server/index.html | 182 ++++++ .../what_is_a_domain_name/index.html | 234 +++++++ .../common_questions/what_is_a_url/index.html | 231 +++++++ .../what_is_a_web_server/index.html | 198 ++++++ .../cascade_and_inheritance/index.html | 135 ++++ files/pt-pt/learn/css/building_blocks/index.html | 359 +++++++++++ .../learn/css/building_blocks/selectors/index.html | 208 +++++++ .../css/building_blocks/styling_tables/index.html | 655 +++++++++++++++++++ .../building_blocks/values_and_units/index.html | 341 ++++++++++ files/pt-pt/learn/css/css_layout/index.html | 453 ++++++++++++++ files/pt-pt/learn/css/estilo_de_texto/index.html | 136 ---- .../first_steps/how_css_is_structured/index.html | 188 ++++++ .../learn/css/first_steps/how_css_works/index.html | 130 ++++ files/pt-pt/learn/css/first_steps/index.html | 92 +++ files/pt-pt/learn/css/howto/css_faq/index.html | 229 +++++++ files/pt-pt/learn/css/howto/faq_de_css/index.html | 229 ------- .../learn/css/howto/generated_content/index.html | 188 ++++++ .../learn/css/styling_text/fundamentals/index.html | 158 +++++ files/pt-pt/learn/css/styling_text/index.html | 136 ++++ .../css/styling_text/styling_lists/index.html | 362 +++++++++++ .../css_basics/index.html | 293 +++++++++ .../dealing_with_files/index.html | 119 ++++ .../how_the_web_works/index.html | 112 ++++ .../html_basics/index.html | 237 +++++++ .../learn/getting_started_with_the_web/index.html | 65 ++ .../installing_basic_software/index.html | 165 +++++ .../javascript_basics/index.html | 413 ++++++++++++ .../publishing_your_website/index.html | 125 ++++ .../the_web_and_web_standards/index.html | 174 ++++++ .../what_will_your_website_look_like/index.html | 112 ++++ .../index.html | 203 ------ files/pt-pt/learn/html/como/index.html | 153 ----- .../add_a_hit_map_on_top_of_an_image/index.html | 203 ++++++ files/pt-pt/learn/html/howto/index.html | 153 +++++ .../criar_hiperligacoes/index.html | 331 ---------- .../demarcar_uma_carta/index.html | 104 ---- .../introducao_ao_html/depurar_html/index.html | 186 ------ .../estrutura_documento_website/index.html | 292 --------- .../estruturar_pagina_de_conteudo/index.html | 107 ---- .../formatacao_avancada_texto/index.html | 691 --------------------- .../pt-pt/learn/html/introducao_ao_html/index.html | 64 -- .../introducao_ao_html/iniciacao_html/index.html | 612 ------------------ .../os_metadados_de_head_em_html/index.html | 346 ----------- .../advanced_text_formatting/index.html | 691 +++++++++++++++++++++ .../creating_hyperlinks/index.html | 331 ++++++++++ .../introduction_to_html/debugging_html/index.html | 186 ++++++ .../document_and_website_structure/index.html | 292 +++++++++ .../getting_started/index.html | 612 ++++++++++++++++++ .../learn/html/introduction_to_html/index.html | 64 ++ .../marking_up_a_letter/index.html | 104 ++++ .../structuring_a_page_of_content/index.html | 107 ++++ .../the_head_metadata_in_html/index.html | 346 +++++++++++ .../learn/html/multimedia_and_embedding/index.html | 69 ++ .../mozilla_splash_page/index.html | 194 ++++++ .../pagina_de_boas_vindas_da_mozilla/index.html | 194 ------ .../video_and_audio_content/index.html | 369 +++++++++++ .../conteudo_de_audio_e_v\303\255deo/index.html" | 369 ----------- .../learn/html/multimedia_e_integracao/index.html | 69 -- files/pt-pt/learn/html/tables/advanced/index.html | 538 ++++++++++++++++ .../index.html | 151 ----- files/pt-pt/learn/html/tables/avancada/index.html | 538 ---------------- files/pt-pt/learn/html/tables/basicos/index.html | 650 ------------------- files/pt-pt/learn/html/tables/basics/index.html | 650 +++++++++++++++++++ .../html/tables/structuring_planet_data/index.html | 151 +++++ .../manipulating_documents/index.html | 160 +++++ .../pt-pt/learn/javascript/first_steps/index.html | 143 +++++ .../learn/javascript/primeiros_passos/index.html | 143 ----- files/pt-pt/learn/no-servidor/django/index.html | 68 -- .../index.html | 406 ------------ .../learn/no-servidor/express_nodejs/index.html | 76 --- .../express_nodejs/introduction/index.html | 539 ---------------- files/pt-pt/learn/no-servidor/index.html | 57 -- .../servidor_node_sem_framework/index.html | 94 --- .../como_funciona_a_internet/index.html | 100 --- .../index.html | 182 ------ files/pt-pt/learn/questoes_comuns/index.html | 131 ---- .../o_que_e_um_nome_de_dominio/index.html | 234 ------- .../o_que_e_um_servidor_da_web/index.html | 198 ------ .../questoes_comuns/o_que_e_um_url/index.html | 231 ------- .../index.html | 122 ---- files/pt-pt/learn/server-side/django/index.html | 68 ++ .../development_environment/index.html | 406 ++++++++++++ .../learn/server-side/express_nodejs/index.html | 76 +++ .../express_nodejs/introduction/index.html | 539 ++++++++++++++++ files/pt-pt/learn/server-side/index.html | 57 ++ .../node_server_without_framework/index.html | 94 +++ .../cross_browser_testing/accessibility/index.html | 607 ++++++++++++++++++ .../cross_browser_testing/index.html | 47 ++ .../acessibilidade/index.html | 607 ------------------ .../teste_cruzado_de_navegador/index.html | 47 -- 105 files changed, 13990 insertions(+), 10561 deletions(-) create mode 100644 files/pt-pt/learn/accessibility/index.html delete mode 100644 files/pt-pt/learn/acessibilidade/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/a_web_e_os_padroes_da_web/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/apresentacao_do_meu_site/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/como_funciona_a_web/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/css_basico/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/elementar_de_javascript/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/html_basicos/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/installing_basic_software/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/lidar_com_ficheiros/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/publicar_o_seu_site_da_web/index.html create mode 100644 files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html create mode 100644 files/pt-pt/learn/common_questions/index.html create mode 100644 files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html create mode 100644 files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html create mode 100644 files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html create mode 100644 files/pt-pt/learn/common_questions/what_is_a_url/index.html create mode 100644 files/pt-pt/learn/common_questions/what_is_a_web_server/index.html create mode 100644 files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html create mode 100644 files/pt-pt/learn/css/building_blocks/index.html create mode 100644 files/pt-pt/learn/css/building_blocks/selectors/index.html create mode 100644 files/pt-pt/learn/css/building_blocks/styling_tables/index.html create mode 100644 files/pt-pt/learn/css/building_blocks/values_and_units/index.html create mode 100644 files/pt-pt/learn/css/css_layout/index.html delete mode 100644 files/pt-pt/learn/css/estilo_de_texto/index.html create mode 100644 files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html create mode 100644 files/pt-pt/learn/css/first_steps/how_css_works/index.html create mode 100644 files/pt-pt/learn/css/first_steps/index.html create mode 100644 files/pt-pt/learn/css/howto/css_faq/index.html delete mode 100644 files/pt-pt/learn/css/howto/faq_de_css/index.html create mode 100644 files/pt-pt/learn/css/howto/generated_content/index.html create mode 100644 files/pt-pt/learn/css/styling_text/fundamentals/index.html create mode 100644 files/pt-pt/learn/css/styling_text/index.html create mode 100644 files/pt-pt/learn/css/styling_text/styling_lists/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html delete mode 100644 files/pt-pt/learn/html/como/adicionar_um_mapa_de_zona_clicavel_numa_imagem/index.html delete mode 100644 files/pt-pt/learn/html/como/index.html create mode 100644 files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html create mode 100644 files/pt-pt/learn/html/howto/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/criar_hiperligacoes/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/demarcar_uma_carta/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/depurar_html/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/estrutura_documento_website/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/estruturar_pagina_de_conteudo/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/formatacao_avancada_texto/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/iniciacao_html/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/os_metadados_de_head_em_html/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/getting_started/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html create mode 100644 files/pt-pt/learn/html/multimedia_and_embedding/index.html create mode 100644 files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html delete mode 100644 files/pt-pt/learn/html/multimedia_and_embedding/pagina_de_boas_vindas_da_mozilla/index.html create mode 100644 files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html delete mode 100644 "files/pt-pt/learn/html/multimedia_e_integracao/conteudo_de_audio_e_v\303\255deo/index.html" delete mode 100644 files/pt-pt/learn/html/multimedia_e_integracao/index.html create mode 100644 files/pt-pt/learn/html/tables/advanced/index.html delete mode 100644 files/pt-pt/learn/html/tables/avaliacao_estruturar_os_dados_dos_planetas/index.html delete mode 100644 files/pt-pt/learn/html/tables/avancada/index.html delete mode 100644 files/pt-pt/learn/html/tables/basicos/index.html create mode 100644 files/pt-pt/learn/html/tables/basics/index.html create mode 100644 files/pt-pt/learn/html/tables/structuring_planet_data/index.html create mode 100644 files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html create mode 100644 files/pt-pt/learn/javascript/first_steps/index.html delete mode 100644 files/pt-pt/learn/javascript/primeiros_passos/index.html delete mode 100644 files/pt-pt/learn/no-servidor/django/index.html delete mode 100644 files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html delete mode 100644 files/pt-pt/learn/no-servidor/express_nodejs/index.html delete mode 100644 files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html delete mode 100644 files/pt-pt/learn/no-servidor/index.html delete mode 100644 files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/como_funciona_a_internet/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/congiurar_um_servidor_de_testes_local/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/o_que_e_um_nome_de_dominio/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/o_que_e_um_servidor_da_web/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/o_que_e_um_url/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa/index.html create mode 100644 files/pt-pt/learn/server-side/django/index.html create mode 100644 files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html create mode 100644 files/pt-pt/learn/server-side/express_nodejs/index.html create mode 100644 files/pt-pt/learn/server-side/express_nodejs/introduction/index.html create mode 100644 files/pt-pt/learn/server-side/index.html create mode 100644 files/pt-pt/learn/server-side/node_server_without_framework/index.html create mode 100644 files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html create mode 100644 files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html delete mode 100644 files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/acessibilidade/index.html delete mode 100644 files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/index.html (limited to 'files/pt-pt/learn') diff --git a/files/pt-pt/learn/accessibility/index.html b/files/pt-pt/learn/accessibility/index.html new file mode 100644 index 0000000000..0b6cbcefd7 --- /dev/null +++ b/files/pt-pt/learn/accessibility/index.html @@ -0,0 +1,86 @@ +--- +title: Acessibilidade +slug: Learn/Acessibilidade +tags: + - ARIA + - Acessibilidade + - Aprender + - Artigos + - CSS + - CodingScripting + - HTML + - JavaScript + - Landing + - Principiantes + - modulo +translation_of: Learn/Accessibility +--- +
{{LearnSidebar}}
+ +

Aprender um pouco de HTML, CSS e JavaScript é útil se quiser tornar-se em um desenvolvedor da web, mas o seu conhecimento precisa de ir mais além do que apenas utilizar as tecnologias - precisa de as utilizar com responsabilidade para maximizar o público dos seus sites da web e não impedir que as utilizem. Para conseguir isso, precisa de aderir às melhores práticas gerais (que são demonstradas através dos tópicos de HTML, CSS, e JavaScript), efetuar teste cruzado de navegador, e considerar a acessibilidade desde o início. Neste módulo, nós iremos abordar o último em detalhes.

+ +

Sumario

+ +

Quando um site é descrito como "acessível", isto significa que um utilizador pode aceder e interagir com todas as funções e conteúdo, sem preocupação de qual o modo que ele acede à web — inclusive e especialmente utilizadores com dificuldades físicas ou mentais.

+ + + +

Como padrão, HTML é acessível, se utilizado corretamente. Acessibilidade web envolve certificar que o conteúdo continua acessível, indiferente de quem ou como se acede à web.

+ +

O Firefox Accessibility Inspector (Inspetor de Acessibilidade Firefox) é uma ferramenta muito útil para verificar problemas de acessibilidade em páginas web. O seguinte vídeo oferece uma boa introdução:

+ +

{{EmbedYouTube("7mqqgIxX_NU")}}

+ +
+

Procura ser um programador de web front-end?

+ +

Nos construimos um curso que inclui toda a informação essencial que precisa para atingir o seu objetivo.

+ +

Começar a Aprender

+
+ +

Pré-requisitos

+ +

Para aproveitar este modulo ao máximo, é boa ideia estudar os primeiros dois módulos dos tópicos HTML, CSS, e JavaScript, ou até melhor, estudar as partes relevantes do modulo de acessibilidade enquanto estuda os tópicos de tecnologia relacionados.

+ +
+

Nota: Se estiver a trabalhar num computador / tablete / outro dispositivo onde não tem a habilidade de criar os seus próprios ficheiros, pode tentar a maioria dos exemplos de código num IDE online como JSBin ou Thimble.

+
+ +

Guias

+ +
+
O que é acessibilidade?
+
Este artigo começa o módulo a definir o que acessibilidade — isto inclui quais os grupos que se tem de considerar e porquê, que ferramentas pessoas usam para aceder à web e como podemos fazer com que acessibilidade seja parte do nosso processo de desenvolvimento da web.
+
HTML: Uma boa base para acessibilidade
+
Uma grande parte de conteúdo da web pode ser feito acessível ao usar os elementos corretos de HTML para os seus usos próprios. Este artigo dá uma vista aprofundada a como HTML pode ser utilizado para certificar a acessibilidade máxima.
+
Melhores práticas de CSS e JavaScript
+
CSS e JavaScript, quando usados corretamente, também têm o potencial de oferecer expriencias da web acessiveis, mas se mal utilizadas podem prejudicar significativamente a acessibilidade. Este artigo descreve algumas das melhores práticas de CSS e JavaScript que devem ser consideradas para garantir que mesmo conteúdos complexos sejam o mais acessíveis possível.
+
Básicos de WAI-ARIA
+
+

No seguimento do artigo anterior, por vezes é difícil criar controlos complexos da interface que envolvem HTML não semântico e conteúdos dinâmicos atualizados em JavaScript. WAI-ARIA é uma tecnologia que pode ajudar com tais problemas, acrescentando semântica que os navegadores e tecnologias de assistência podem reconhecer e utilizar para que os utilizadores saibam o que se está a passar. Aqui mostraremos como utilizá-la a um nível básico para melhorar a acessibilidade.

+
+
Acessibilidade em multimédia
+
Outra categoria de conteúdos que pode criar problemas de acessibilidade é a multimédia — os conteúdos de vídeo, áudio e imagem precisam de receber alternativas textuais adequadas, para que possam ser compreendidos pelas tecnologias de assistência e pelos seus utilizadores. Este artigo mostra como.
+
Acessibilidade em moveis
+
Com o acesso à web em dispositivos móveis a ser tão popular, e com plataformas populares como o iOS e o Android a terem ferramentas de acessibilidade completas, é importante considerar a acessibilidade do seu conteúdo web nestas plataformas.  Este artigo analisa as considerações de acessibilidade específicas para dispositivos móveis.
+
+ +

Avaliações

+ +
+
Troubleshooting de Acessibilidade
+
Na avaliação para este modulo, nos apresentamos um site simples com uns problemas de acessibilidade que tem de diagonisar e resolver.
+
+ +

Ver também

+ + diff --git a/files/pt-pt/learn/acessibilidade/index.html b/files/pt-pt/learn/acessibilidade/index.html deleted file mode 100644 index 0b6cbcefd7..0000000000 --- a/files/pt-pt/learn/acessibilidade/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Acessibilidade -slug: Learn/Acessibilidade -tags: - - ARIA - - Acessibilidade - - Aprender - - Artigos - - CSS - - CodingScripting - - HTML - - JavaScript - - Landing - - Principiantes - - modulo -translation_of: Learn/Accessibility ---- -
{{LearnSidebar}}
- -

Aprender um pouco de HTML, CSS e JavaScript é útil se quiser tornar-se em um desenvolvedor da web, mas o seu conhecimento precisa de ir mais além do que apenas utilizar as tecnologias - precisa de as utilizar com responsabilidade para maximizar o público dos seus sites da web e não impedir que as utilizem. Para conseguir isso, precisa de aderir às melhores práticas gerais (que são demonstradas através dos tópicos de HTML, CSS, e JavaScript), efetuar teste cruzado de navegador, e considerar a acessibilidade desde o início. Neste módulo, nós iremos abordar o último em detalhes.

- -

Sumario

- -

Quando um site é descrito como "acessível", isto significa que um utilizador pode aceder e interagir com todas as funções e conteúdo, sem preocupação de qual o modo que ele acede à web — inclusive e especialmente utilizadores com dificuldades físicas ou mentais.

- - - -

Como padrão, HTML é acessível, se utilizado corretamente. Acessibilidade web envolve certificar que o conteúdo continua acessível, indiferente de quem ou como se acede à web.

- -

O Firefox Accessibility Inspector (Inspetor de Acessibilidade Firefox) é uma ferramenta muito útil para verificar problemas de acessibilidade em páginas web. O seguinte vídeo oferece uma boa introdução:

- -

{{EmbedYouTube("7mqqgIxX_NU")}}

- -
-

Procura ser um programador de web front-end?

- -

Nos construimos um curso que inclui toda a informação essencial que precisa para atingir o seu objetivo.

- -

Começar a Aprender

-
- -

Pré-requisitos

- -

Para aproveitar este modulo ao máximo, é boa ideia estudar os primeiros dois módulos dos tópicos HTML, CSS, e JavaScript, ou até melhor, estudar as partes relevantes do modulo de acessibilidade enquanto estuda os tópicos de tecnologia relacionados.

- -
-

Nota: Se estiver a trabalhar num computador / tablete / outro dispositivo onde não tem a habilidade de criar os seus próprios ficheiros, pode tentar a maioria dos exemplos de código num IDE online como JSBin ou Thimble.

-
- -

Guias

- -
-
O que é acessibilidade?
-
Este artigo começa o módulo a definir o que acessibilidade — isto inclui quais os grupos que se tem de considerar e porquê, que ferramentas pessoas usam para aceder à web e como podemos fazer com que acessibilidade seja parte do nosso processo de desenvolvimento da web.
-
HTML: Uma boa base para acessibilidade
-
Uma grande parte de conteúdo da web pode ser feito acessível ao usar os elementos corretos de HTML para os seus usos próprios. Este artigo dá uma vista aprofundada a como HTML pode ser utilizado para certificar a acessibilidade máxima.
-
Melhores práticas de CSS e JavaScript
-
CSS e JavaScript, quando usados corretamente, também têm o potencial de oferecer expriencias da web acessiveis, mas se mal utilizadas podem prejudicar significativamente a acessibilidade. Este artigo descreve algumas das melhores práticas de CSS e JavaScript que devem ser consideradas para garantir que mesmo conteúdos complexos sejam o mais acessíveis possível.
-
Básicos de WAI-ARIA
-
-

No seguimento do artigo anterior, por vezes é difícil criar controlos complexos da interface que envolvem HTML não semântico e conteúdos dinâmicos atualizados em JavaScript. WAI-ARIA é uma tecnologia que pode ajudar com tais problemas, acrescentando semântica que os navegadores e tecnologias de assistência podem reconhecer e utilizar para que os utilizadores saibam o que se está a passar. Aqui mostraremos como utilizá-la a um nível básico para melhorar a acessibilidade.

-
-
Acessibilidade em multimédia
-
Outra categoria de conteúdos que pode criar problemas de acessibilidade é a multimédia — os conteúdos de vídeo, áudio e imagem precisam de receber alternativas textuais adequadas, para que possam ser compreendidos pelas tecnologias de assistência e pelos seus utilizadores. Este artigo mostra como.
-
Acessibilidade em moveis
-
Com o acesso à web em dispositivos móveis a ser tão popular, e com plataformas populares como o iOS e o Android a terem ferramentas de acessibilidade completas, é importante considerar a acessibilidade do seu conteúdo web nestas plataformas.  Este artigo analisa as considerações de acessibilidade específicas para dispositivos móveis.
-
- -

Avaliações

- -
-
Troubleshooting de Acessibilidade
-
Na avaliação para este modulo, nos apresentamos um site simples com uns problemas de acessibilidade que tem de diagonisar e resolver.
-
- -

Ver também

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/a_web_e_os_padroes_da_web/index.html b/files/pt-pt/learn/comecar_com_a_web/a_web_e_os_padroes_da_web/index.html deleted file mode 100644 index 928a960b97..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/a_web_e_os_padroes_da_web/index.html +++ /dev/null @@ -1,174 +0,0 @@ ---- -title: A Web e os padrões da Web -slug: Learn/Comecar_com_a_Web/A_web_e_os_padroes_da_web -tags: - - Aprender - - Beginner - - Front-end - - Normas da Web - - Padrões da Web - - Web -translation_of: Learn/Getting_started_with_the_web/The_web_and_web_standards ---- -

{{learnsidebar}}

- -

Este artigo fornece informação útil sobre a Web - como surgiu, o que são as tecnologias padrão da Web, como trabalham em conjunto, porque é que web developer é uma excelente carreira a escolher, e que melhores práticas irá aprender através do curso.

- -

História resumida da Web

- -

Vamos manter isto muito breve, pois existem relatos muito (mais) detalhados da história da web lá fora, aos quais faremos referência mais tarde (tente também procurar por "história da web" no seu motor de busca favorito e veja o que obtém, se estiver interessado em mais detalhes).

- -

No final da década de 1960, o exército dos EUA desenvolveu uma rede de comunicação chamada ARPANET. Esta pode ser considerada uma precursora da Web, uma vez que funcionava na {{Interwiki("wikipedia", "Comutação de pacotes", "comutação de pacotes")}}, e incluía a primeira implementação do conjunto de protocolos {{Interwiki("wikipedia", "TCP/IP", "TCP/IP")}}. Estas duas tecnologias formam a base da infra-estrutura sobre a qual a Internet está construída.

- -

Em 1980, Tim Berners-Lee (frequentemente referido como TimBL) escreveu um programa de caderno de notas chamado ENQUIRE, que apresentava o conceito de ligações entre os diferentes nódulos. Soa familiar?

- -

Avançando para 1989, e a TimBL escreveu Information Management: A Proposal e HyperText at CERN; estas duas publicações em conjunto forneceram o pano de fundo para a forma como a web funcionaria. Receberam interesse suficiente para convencer os chefes do TimBL a permitir-lhe avançar e criar um sistema global de hipertexto.

- -

No final de 1990, TimBL tinha criado todas as coisas necessárias para executar a primeira versão da web - HTTP, HTML, o primeiro navegador web, que se chamava {{Interwiki("wikipedia", "WorldWideWeb", "WorldWideWeb")}}, um servidor HTTP, e algumas páginas web para ver.

- -

Nos anos que se seguiram, a web explodiu, com vários navegadores a serem lançados, milhares de servidores web a serem criados, e milhões de páginas web a serem criadas. OK, este é um resumo muito simples do que aconteceu, mas prometi-vos um breve resumo.

- -

Um último dado significativo a partilhar é que em 1994, o TimBL fundou o {{Interwiki("wikipedia", "W3C", "World Wide Web Consortium")}} (W3C), uma organização que reúne representantes de muitas empresas tecnológicas diferentes para trabalharem em conjunto na criação de especificações tecnológicas para a web. Depois disso seguiram-se outras tecnologias, tais como CSS e JavaScript, e a web começou a parecer-se mais com a web que conhecemos hoje.

- -

Os padrões da Web

- -

As normas / padrões da web são as tecnologias que utilizamos para construir websites. Estas normas existem como longos documentos técnicos chamados especificações, que detalham exactamente como a tecnologia deve funcionar. Estes documentos não são muito úteis para aprender a utilizar as tecnologias que descrevem (é por isso que temos sites como a MDN Web Docs), mas em vez disso destinam-se a ser utilizados por engenheiros de software para implementar estas tecnologias (geralmente em navegadores).

- -

Por exemplo, o HTML Living Standard descreve exactamente como o HTML (todos os elementos HTML, e as suas APIs associadas, e outras tecnologias circundantes) deve ser implementado.

- -

As normas Web são criadas por organismos de normas — instituições que convidam grupos de pessoas de diferentes empresas tecnológicas a juntarem-se e acordarem sobre a melhor forma de como as tecnologias devem funcionar para cumprir todos os seus casos de utilização. O W3C é o organismo de normas Web mais conhecido, mas existem outros como o WHATWG (que foi responsável pela modernização da linguagem HTML), ECMA (que publica a norma para ECMAScript, na qual o JavaScript se baseia), Khronos (que publica tecnologias para gráficos 3D, como o WebGL), e outros.

- -

Standards "abertos"

- -

Um dos aspetos chave das normas web, que o TimBL e o W3C acordaram desde o início, é que a web (e as tecnologias web) devem ser livres de contribuir e utilizar, e não sobrecarregadas por patentes / licenciamento. Portanto, qualquer pessoa pode escrever o código para construir um website gratuitamente, e qualquer pessoa pode contribuir para o processo de criação de normas, onde as especificações são escritas.

- -

Porque as tecnologias web são criadas abertamente, numa colaboração entre várias empresas, isso significa que nenhuma empresa as consegue controlar, que é fantástico. Não se quer que uma única empresa decida subitamente colocar a web inteira atrás de uma paywall, ou lançar uma nova versão de HTML que todos têm de comprar para continuar a fazer websites, ou pior ainda, decidindo apenas que já não estão interessados e simplesmente desligando a web.

- -

Isto permite que a web continue a ser um recurso público disponível gratuitamente.

- -

Não quebre a web

- -

Outra frase que ouvirá em torno das normas abertas da web é "não quebre a web" — a ideia é que qualquer nova tecnologia web que seja introduzida deve ser retro compatível com o que existia antes (ou seja, os antigos websites continuarão a funcionar), e com o que existe atualmente (as futuras tecnologias, por sua vez, serão compatíveis com o que temos atualmente). Ao percorrer o material de aprendizagem aqui apresentado, começará a aprender como isto se torna possível com algum trabalho de conceção e implementação muito inteligente.

- -

Ser um web developer é bom

- -

A indústria da web é um mercado muito atrativo para entrar se estiver à procura de um emprego. Números recentemente publicados dizem que existem atualmente cerca de 19 milhões de web developers no mundo, e esse número é previsto mais que dobrar na próxima década. E, ao mesmo tempo, há uma escassez de competências na indústria — portanto, que melhor altura para aprender a desenvolvimento web?

- -

No entanto, nem tudo é brincadeira — construir sites é uma atividade mais complicada do que costumava ser, e terá de dedicar algum tempo ao estudo de todas as diferentes tecnologias que precisa de utilizar, todas as técnicas e melhores práticas que precisa de conhecer, e todos os padrões típicos que será necessário implementar. Vai levar alguns meses para começar realmente a ser proficiente, e depois terá de continuar a aprender para que o seu conhecimento se mantenha atualizado com todas as novas ferramentas e funcionalidades que aparecem na plataforma web, e continuar a praticar e a aperfeiçoar a sua arte.

- -

A única constante é a mudança.

- -

Isto parece-lhe difícil? Não se preocupe — o nosso objetivo é dar-lhe tudo o que precisa de saber para começar, e as coisas ficarão mais fáceis. Assim que aceitar a constante mudança e incerteza da web, começará a divertir-se. Como parte da comunidade web, terá uma rede de contactos e material útil para o ajudar, e começará a desfrutar das possibilidades criativas que ela lhe traz.

- -

Agora é um criativo digital. Desfrute da experiência.

- -

Sinopse das tecnologias modernas da Web

- -

Há uma série de tecnologias a aprender se quiser ser um programador da web de front-end. Nesta secção iremos descrevê-las brevemente. Para uma explicação mais detalhada de como algumas delas funcionam em conjunto, leia o nosso artigo Como funciona a web.

- - - -

É provável que esteja a ler estas palavras dentro de um navegador neste preciso momento (a menos que o tenha imprimido, ou que esteja a utilizar tecnologia de assistência, tal como um leitor de ecrã para o ler). Os navegadores são os programas de software que as pessoas utilizam para consumir a web, e incluem o Firefox, Chrome, Opera, Safari, e Edge.

- -

HTTP

- -

Hypertext Transfer Protocol, ou HTTP, é um protocolo de transmissão de mensagens que permite aos navegadores Web comunicarem com servidores (onde os websites são armazenados). Uma conversa típica é algo como

- -
"Hello web server. Can you give me the files I need to render bbc.co.uk"?
-
-"Sure thing web browser — here you go"
-
-[Downloads files and renders web page]
- -

A sintaxe das mensagens HTTP (chamadas pedidos e respostas) não é tão legível para o ser humano, mas isto dá-lhe a ideia básica.

- -

HTML, CSS, e JavaScript

- -

HTML, CSS, e JavaScript são as três tecnologias principais que irá usar para construir um site:

- - - -

Tooling

- -

Uma vez aprendidas as tecnologias de base que podem ser usadas para construir páginas web (como HTML, CSS, e JavaScript), em breve começará a deparar-se com várias ferramentas que podem ser usadas para tornar o seu trabalho mais fácil ou mais eficiente. Os exemplos incluem:

- - - -

Linguagens de lado de servidor e frameworks

- -

HTML, CSS, e JavaScript são linguagens de front-end (ou client-side), que significa que eles são processados pelo navegador para produzir a interface dum website que os seus utilizadores possam usar.

- -

Há outra classe de línguas chamada de back-end (ou línguas do lado do servidor), o que significa que são executadas no servidor antes de o resultado ser então enviado para o navegador para ser exibido. Uma utilização típica para uma linguagem do lado do servidor é obter alguns dados de uma base de dados e gerar algum HTML para conter os dados, antes de depois enviar o HTML para o navegador para o exibir ao utilizador.

- -

Exemplos de linguagens de lado de servidor incluem C#, Python, PHP e Java.

- -

As melhores práticas da Web

- -

Falámos brevemente sobre as tecnologias que irá utilizar para construir sítios web. Agora vamos discutir as melhores práticas que deverá empregar para se certificar de que está a utilizar essas tecnologias o melhor possível.

- -

Ao fazer desenvolvimento web, a principal causa de incerteza advém do facto de não se saber que combinação de tecnologia cada utilizador utilizará para visualizar o seu site:

- - - -

Como não sabe exatamente o que os seus utilizadores irão usar, precisa de planear defensivamente - tornar o seu site tão flexível quanto possível, para que todos os utilizadores acima mencionados possam fazer uso dele, mesmo que nem todos possam ter a mesma experiência. Em resumo, estamos a tentar fazer com que a web funcione para todos, tanto quanto possível.

- -

Encontrará os conceitos abaixo em algum momento dos seus estudos.

- - - -

Ver também

- - - - diff --git a/files/pt-pt/learn/comecar_com_a_web/apresentacao_do_meu_site/index.html b/files/pt-pt/learn/comecar_com_a_web/apresentacao_do_meu_site/index.html deleted file mode 100644 index a5eacc3afa..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/apresentacao_do_meu_site/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Qual será a aparência do seu site da Web? -slug: Learn/Comecar_com_a_Web/Apresentacao_do_meu_site -tags: - - Aprender - - Beginner - - Conteúdo - - Design - - Planear - - Tipos de Letra - - 'l10n:priority' -translation_of: Learn/Getting_started_with_the_web/What_will_your_website_look_like ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Installing_basic_software", "Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web")}}
- -
-

Este artigo descreve o planeamento e conceptualização necessários antes de escrever o código do site da internet, incluindo "Que informação é que o meu site oferece?", "Quais os tipos de letra e cores que eu quero?" e ​​"O que é que o meu site faz?"

-
- -

Antes de tudo: planeamento

- -

Antes de fazer o que quer que seja, precisa de algumas ideias. O que é que o seu site realmente deve fazer? Um site pode fazer qualquer coisa, mas para a sua primeira tentativa, procure manter as coisas simples. Vamos começar a criar uma página web simples com um cabeçalho, uma imagem e alguns parágrafos.

- -

Para começar, irá precisar de responder a estas questões:

- -
    -
  1. De que se trata o seu site da Web? Gosta de cães, Nova Iorque, ou Pac-Man?
  2. -
  3. Que informação é que vai apresentar acerca o assunto? Escreva um título e alguns parágrafos, e pense numa imagem que gostaria de mostrar na sua página.
  4. -
  5. Como será apresentado o seu site da Web, em termos simples de alto nível? Qual é a cor de fundo? Que tipo de letra é apropriado: formal, desenhos, negrito e tom alto, subtil?
  6. -
- -
-

Nota: Projetos complexos precisam de diretrizes detalhadas que abordem todos os detalhes de cores, tipos de letra, espaçamento entre elementos de uma página, estilo de escrita apropriado, e assim por diante. Isto às vezes é chamado guia de desenho ou livro de marca, e pode ver um exemplo em  Firefox OS - Orientações (inglês).

-
- -

Esboçar o seu desenho

- -

A seguir, pegue numa caneta e papel e crie um esboço do layout do seu site. Para a sua primeira página, não há muito o que esboçar, mas deve adquirir o hábito de fazer isso agora. Isto é mesmo uma grande ajuda — não tem que ser um Van Gogh!

- -

- -
-

Nota: Mesmo em sites a sérios, complexos, a equipa de design costuma começar com esboços grosseiros em papel e mais tarde constrói maquetas digitais com um editor de imagem ou tecnologias web.

- -

Equipas de desenvolvimento web geralmente incluem um designer gráfico e um designer {{Glossary("UX", "user-experience")}} (UX). Obviamente, os designers gráficos montam os elementos visuais do site. Designers UX têm um papel mais abstrato, que consiste em abordar a forma como utilizadores vão experimentar e interagir com o site.

-
- -

Escolha do conteúdo

- -

Nesta altura, é boa ideia começar a criar o conteúdo que virá a aparecer na sua página da internet.

- -

Texto

- -

Ainda deve ter o parágrafo e títulos de há bocado. Mantenha-os por perto.

- -

Cor do tema

- -

Para escolher uma cor, vá ao Seletor de Cores e encontre uma cor de que gosta. Quando clicar numa cor, vai ver um código estranho com seis caracteres, tal como #660066. Este é um código hexadecimal que representa um tom de cor específico. Aponte o código num local de fácil acesso.

- -

- -

Imagens

- -

Para escolher uma imagem, pesquise Images no Google procure algo adequado.

- -
    -
  1. Quando encontrar a imagem que quer, clique nela.
  2. -
  3. Prima o botão Ver imagem.
  4. -
  5. Na página seguinte, carregue o botão direito do rato (Ctrl + clique nos Mac), escolha Guardar imagem como..., e escolha um lugar seguro para guardar a imagem. Em alternativa, copie o endereço da imagem da barra de endereço do seu navegador para a utilizar mais tarde.
  6. -
- -

- -

- -
-

Nota: A maioria das imagens, incluindo na pesquisa de Imagens do Google, estão protegidas por direitos de autor. Para reduzir probabilidades de violar estes direitos, pode usar o filtro de licença do  Google. Primeiro, clique em Ferramentas de Pesquisa, e depois em Direitos de utilização:

- -

-
- -

Tipo de letra

- -

Para escolher um tipo de letra:

- -
    -
  1. Vá ao Google Fonts e deslize para baixo até encontrar um de que goste. Também pode usar os controlos à direita para filtrar resultados.
  2. -
  3. Clique no ícone "mais" (Adicionar) perto do tipo de letra que escolheu.
  4. -
  5. Clique no botão "* Family Selected" no painel no fim da página ("*" será o número de tipos de letra selecionados).
  6. -
  7. Na caixa apresentada, copie as linhas de código que o Google lhe dará para um editor de texto e guarde para utilizar mais tarde.
  8. -
- -

- -

- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Installing_basic_software", "Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web")}}
- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/como_funciona_a_web/index.html b/files/pt-pt/learn/comecar_com_a_web/como_funciona_a_web/index.html deleted file mode 100644 index 69fe6b79fa..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/como_funciona_a_web/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Como funciona a Web -slug: Learn/Comecar_com_a_Web/Como_funciona_a_Web -tags: - - Aprender - - Beginner - - Cliente - - DNS - - HTTP - - IP - - Infraestrutura - - Servidor - - TCP - - 'l10n:priority' -translation_of: Learn/Getting_started_with_the_web/How_the_Web_works ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
- -
-

Como a Web funciona, fornece uma visualização simplificada do que acontece quando visualiza uma página da Web num navegador da Web no seu computador ou dispositivo móvel.

-
- -

Esta teoria não é essencial para escrever o código da Web em curto prazo, mas em pouco tempo, irá realmente começar a beneficiar da compreensão do que está a acontecer em segundo plano.

- -

Servidores e clientes

- -

Os computadores ligados à Web são chamados de clientes e servidores. Um diagrama simplificado de como eles interagem, parece-se como isto:

- -

- - - -

As outras partes da caixa de ferramentas

- -

O cliente e o servidor que descrevemos acima não contam toda a história. Há muitas outras partes envolvidas, e iremos descrevê-las em baixo.

- -

Por enquanto, vamos imaginar que a Web é uma estrada. Num extremo da estrada está o cliente, que é como a sua casa. Na outra extremidade da estrada está o servidor, que é uma loja na qual deseja comprar algo.

- -

- -

Além do cliente e do servidor, nós também precisamos cumprimentar:

- - - -

Então, o que acontece exatamente?

- -

Quando escreve um endereço web no seu browser (para a nossa analogia isso é como caminhar até à loja):

- -
    -
  1. O navegador vai para o servidor DNS, e encontra o endereço real do servidor onde o sítio web vive (encontra o endereço da loja).
  2. -
  3. O navegador envia uma mensagem de pedido HTTP ao servidor, pedindo-lhe que envie uma cópia do website ao cliente (vai à loja e encomenda a sua mercadoria). Esta mensagem e todos os outros dados enviados entre o cliente e o servidor, é enviada através da sua ligação à Internet utilizando TCP/IP.
  4. -
  5. Desde que o servidor aprove o pedido do cliente, o servidor envia ao cliente uma mensagem "200 OK", o que significa "Claro que pode olhar para esse website! Aqui está", e depois começa a enviar os ficheiros do sítio web para o navegador como uma série de pequenos pedaços chamados packets / pacotes de dados (a loja dá-lhe os seus bens, e você trá-los de volta para a sua casa).
  6. -
  7. O navegador monta os pequenos pedaços num website completo e mostra-lho (os bens chegam à sua porta — coisas novas e brilhantes, espetacular!).
  8. -
- -

DNS explicado

- -

Os verdadeiros endereços web não são os nomes agradáveis e memoráveis que escreve na sua barra de endereços para encontrar os seus sítios web favoritos. São números especiais que têm este aspeto: 63.245.215.20.

- -

Isto chama-se um {{Glossary("IP Address", "Endereço IP")}}, e representa uma localidade única na web. No entanto, não é muito fácil de lembrar, pois não? É por isso que foram inventados os Servidores de Nome de Domínio. Estes são servidores especiais que correspondem a um endereço web que digita no seu browser (como "mozilla.org") ao endereço real (IP) do website.

- -

Os websites podem ser acedidos diretamente através dos seus endereços IP. Pode encontrar o endereço IP de um sítio web digitando o seu domínio numa ferramenta como o IP Checker.

- -

A domain name is just another form of an IP address

- -

Packets explicados

- -

Anteriormente utilizámos o termo "packets" para descrever o formato em que os dados são enviados do servidor para o cliente. O que é que queremos dizer aqui? Basicamente, quando os dados são enviados através da web, são enviados como milhares de pequenos pedaços, para que muitos utilizadores da web possam descarregar o mesmo website ao mesmo tempo. Se os sítios web fossem enviados como um único grande pedaço, apenas um utilizador poderia descarregar um de cada vez, o que obviamente tornaria a web muito ineficiente e não muito divertida de utilizar.

- -

Ver também

- - - -

Créditos

- -

Street photo: Street composing, por Kevin D.

- -

{{PreviousMenu("Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/css_basico/index.html b/files/pt-pt/learn/comecar_com_a_web/css_basico/index.html deleted file mode 100644 index 9b401915f7..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/css_basico/index.html +++ /dev/null @@ -1,293 +0,0 @@ ---- -title: CSS - Essencial -slug: Learn/Comecar_com_a_Web/CSS_basico -tags: - - Aprender - - Beginner - - CSS - - CodingScripting - - Estilo - - 'I10n:priority' - - Web -translation_of: Learn/Getting_started_with_the_web/CSS_basics ---- -
{{LearnSidebar}} -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web")}}
-
- -
-

CSS (Folhas de Estilo em Cascata) é o código que se utiliza para estilizar a sua página da Web. CSS - Elementar guia-o através do que precisa para começar. Vamos responder a perguntas deste género: Como é que eu coloco o meu texto a preto ou vermelho? Como é que eu faço para que o meu conteúdo apareça neste lugar do ecrã? Como é que eu decoro a minha página da Web, com cores e imagens de fundo?

-
- -

Então, o que realmente é o CSS?

- -

Tal como o HTML, o CSS não é bem uma linguagem de programação; também não é uma linguagem de demarcação. É uma linguagem de folha de estilos. Isto significa que permite aplicar estilos seletivamente aos elementos nos documentos HTML. Por exemplo, para selecionar todos os elementos do parágrafo numa página HTML e transformar o texto dentro deles em vermelho, iria escrever este CSS:

- -
p {
-  color: red;
-}
- -

Vamos tentar: copie e cole estas três linhas de CSS num novo ficheiro do editor de texto, depois grave com o nome style.css na diretoria styles.

- -

Mas ainda é preciso aplicar este CSS ao seu documento HTML. Se não, os estilos CSS não vão afetar a forma como o seu navegador apresenta o documento HTML. (Se não tem seguido o nosso projeto, leia Lidar com ficheiros e HTML - Essencial para saber o que fazer primeiro)

- -
    -
  1. Abra o seu ficheiro index.html e cole a linha seguinte no cabeçalho (isto é, entre as marcas <head> e </head>): - -
    <link href="styles/style.css" rel="stylesheet" type="text/css">
    -
  2. -
  3. Guarde o ficheiro index.html e aceda-lhe no seu navegador. Deverá ver algo deste género:
  4. -
- -

A mozilla logo and some paragraphs. The paragraph text has been styled red by our css.O texto dos seus parágrafos ficou vermelho. Parabéns! Acabou de escrever com sucesso o seu primeiro CSS.

- -

Anatomia de um conjunto de regras de CSS

- -

Vejamos o CSS acima com um pouco mais de detalhe:

- -

- -

A esta estrutura dá-se o nome conjunto de regras (geralmente, "regra" para abreviar). Repare nos nomes de cada parte:

- -
-
Seletor
-
Neste caso, é o nome do elemento HTML, no início do conjunto de regras. Seleciona o(s) elemento(s) a que vai ser aplicado o estilo (neste caso, todos os elementos p). Para dar estilo a outro elemento, muda-se o seletor.
-
Declaração
-
Trata-se de uma única regra, como  color: red;, que especifica as propriedades que se pretendem modificar no elemento.
-
Propriedades
-
São as formas como se pode estilizar o elemento HTML (Neste caso, color é uma propriedade dos elementos {{htmlelement("p")}}). Em CSS, pode escolher que propriedades pretende modificar na regra.
-
Valor da propriedade
-
À direita da propriedade, depois dos dois pontos (:), temos o valor da propriedade, que escolhe uma das possíveis aparências que a propriedade pode indicar (há muitos mais valores para color além de red).
-
- -

Repare em outros aspetos importantes da sintaxe:

- - - -

Para modificar múltiplas propriedades, basta separá-las com o ponto e vírgula, assim:

- -
p {
-  color: red;
-  width: 500px;
-  border: 1px solid black;
-}
- -

Selecionar múltiplos elementos

- -

Também pode selecionar vários elementos e aplicar um conjunto de regras único para todos eles. Inclua múltiplos seletores separados por vírgulas. Por exemplo:

- -
p, li, h1 {
-  color: red;
-}
- -

Diferentes tipos de seletor

- -

Há muitos tipos diferentes de seletor. Por cima, apenas olhámos para seletores de elementos, que selecionam todos os elementos de determinado tipo no documento HTML a que são aplicados. Mas podemos fazer seleções mais específicas. Em baixo, estão alguns dos tipos mais comuns de seletores:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do seletorO que é que este selecionaExemplo
Seletor de elemento (também chamado seletor de etiqueta ou tipo)Todos os elementos HTML do tipo especificado.p
- Seleciona todos os elementos <p>
Seletor de ID O elemento da página com o ID especificado (numa página HTML, só pode haver um elemento para cada ID e vice-versa).#my-id
- Seleciona <p id="my-id"> ou <a id="my-id"> (não devem existir ambos na mesma página)
Seletor de classeSeleciona o(s) elementos(s) da página com a classe especificada (é possível haver elementos diferentes com a mesma classe)..my-class
- Seleciona <p class="my-class"> e também <a class="my-class">
Seletor de atributoSeleciona o(s) elementos(s) que tenham o atributo dado.img[src]
- Seleciona <img src="myimage.png"> mas não seleciona <img>
Seletor de Pseudo-classeO(s) elemento(s) especificado(s), mas só quando estiverem no estado indicado. Ex: quando se tem cursor do rato sobre eles.a:hover
- Seleciona <a>, mas só quando o cursor está sobre o link.
- -

Existem muitos mais seletores para explorar, e pode encontrar uma lista mais detalhada no nosso Guia de seletores.

- -

Fonte e texto

- -

Agora que explorámos as bases do CSS, vamos acrescentar regras e informação ao nosso ficheiro style.css para que o exemplo tenha boa apresentação.

- -
    -
  1. Primeiro, volte atrás e encontre o output de Google Fonts que guardou num lugar seguro. Acrescente o elemento {{htmlelement("link")}} no cabeçalho do index.html (entre etiquetas <head> e </head>). - -
    <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    -
  2. -
  3. De seguida, apague a regra que tinha no ficheiro style.css. Foi um bom teste, mas a cor vermelha não ficou muito bem.
  4. -
  5. Insira as linhas que se seguem, substituindo a linha de substituição pela linha font-family que obteve no site Google Fonts. (font-family indica o nome do tipo de letra). Esta regra estabelece um tamanho e tipo de letra global, em toda a página, já que o elemento <html> é o elemento raiz e todos os elementos aninhados herdam font-size e font-family: -
    html {
    -  font-size: 10px; /* px significa 'píxeis': o tamnho da letra base é duma altura de 10 píxeis */
    -  font-family: placeholder: aqui deve aparecero resto do output do Google fonts
    -}
    - -
    -

    Nota: num documento CSS, tudo o que esteja entre /* e */ é um comentário de CSS, que o navegador ignora quando processa o código. Os comentários servem para escrever notas úteis sobre o que está a fazer.

    -
    -
  6. -
  7. Agora estabelecemos o tamanho da letra para elementos textuais no corpo do HTML: ({{htmlelement("h1")}}, {{htmlelement("li")}}, e {{htmlelement("p")}}). Também vamos centrar o texto dos nossos títulos e especificar altura da linha de texto e espaçamento entre letras no corpo para o tornar mais legível: -
    h1 {
    -  font-size: 60px;
    -  text-align: center;
    -}
    -
    -p, li {
    -  font-size: 16px;
    -  line-height: 2;
    -  letter-spacing: 1px;
    -}
    -
  8. -
- -

Pode ajustar os valores de px conforme achar que fica melhor, mas em geral, o design deve ter esta aparência:

- -

a mozilla logo and some paragraphs. a sans-serif font has been set, the font sizes, line height and letter spacing are adjusted, and the main page heading has been centered

- -

Caixas, caixas, é tudo sobre caixas

- -

Quando escreve CSS, poderá notar que a maior parte do esforço é referente a caixas — configurar o seu tamanho, cor, posição, etc. Pode pensar na maioria dos elementos de HTML da sua página como caixas colocadas umas sobre a outras.

- -

a big stack of boxes or crates sat on top of one another

- -

Sem surpresa, a disposição de elementos em CSS assenta principalmente num modelo de caixa. Cada um dos blocos que ocupa espaço na sua página tem propriedades como:

- - - -

three boxes sat inside one another. From outside to in they are labelled margin, border and padding

- -

Nesta secção também vamos usar:

- - - -

Portanto, vamos começar e acrescentar algum CSS à nossa página! Acrescente as novas regras no fim do ficheiro e não tenha medo de mudar os valores para ver como fica.

- -

Alterar a cor da página

- -
html {
-  background-color: #00539F;
-}
- -

Esta regra estabelece uma cor de fundo na página inteira. Mude o código de cor para aquele que escolheu quando planeou o seu site.

- -

Ordenar o corpo

- -
body {
-  width: 600px;
-  margin: 0 auto;
-  background-color: #FF9500;
-  padding: 0 20px 20px 20px;
-  border: 5px solid black;
-}
- -

Agora o elemento {{htmlelement("body")}}. Há várias declarações, então vamos ver uma de cada vez:

- - - -

Posicionar e estilizar o título da nossa página principal

- -
h1 {
-  margin: 0;
-  padding: 20px 0;
-  color: #00539F;
-  text-shadow: 3px 3px 1px black;
-}
- -

Deve ter notado que há espaço em branco horrível no topo do conteúdo da página. Isto acontece porque o navegador aplica estilo por omissão ao elemento {{htmlelement("h1")}} (entre outros), mesmo que não se tenha aplicado qualquer CSS! Embora isso possa parecer má ideia, na prática até uma página sem folha de estilos tem que ter alguma legibilidade. Para nos livrarmos deste espaço, colocamos margin: 0;.

- -

De seguida, colocámos o preenchimento por cima e por baixo a 20 píxeis, e demos ao texto a mesma cor que a cor de fundo do elemento {{htmlelement("html")}}.

- -

Utilizámos uma propriedade interessante, text-shadow, que aplica sombreado ao texto de um elemento. Estes são os quatro valores da mesma:

- - - -

Novamente, tente experimentar os valores para ver como fica!

- -

Centrar a imagem

- -
img {
-  display: block;
-  margin: 0 auto;
-}
- -

Por fim, vamos centrar a imagem para ficar melhor. Utilizámos o truque de colocar margin: 0 auto como fizemos com o corpo, mas temos que fazer outra coisa. O elemento {{htmlelement("body")}} está ao nível de bloco, ou seja, ocupa toda a largura da página e podem ser-lhe aplicados valores de margem, e outros valores de espaçamento. Por outro lado, as imagens são elemento em linha, a que não se podem aplicar estes valores. Então, para a margem ser aplicada à imagem, temos que lhe atribuir comportamento ao nível do bloco com display: block;.

- -
-

Nota: Estas instruções assumem que está a usar uma imagem mais pequena que a largura do corpo (600 píxeis). Se for maior, vai transbordar do corpo e ocupar espaço no resto da página. Para retificar isto, pode 1) reduzir a largura da imagem com um programa de edição gŕafica, ou 2) reduzir a imagem com CSS utilizando a propriedade {{cssxref("width")}} no elemento <img> com um valor mais pequeno, como 400 px;.

-
- -
-

Nota: não se preocupe se ainda não entende display: block; e a distinção entre bloco e em linha (block-level/inline). Irá perceber à medida que estuda o CSS com mais profundidade. Pode descobrir mais sobre os diferentes valores de display na página de referência de display.

-
- -

Conclusão

- -

Se seguiu as instruções nesta página, a sua página deve ter este aspeto (e pode ver a nossa versão aqui):

- -

a mozilla logo, centered, and a header and paragraphs. It now looks nicely styled, with a blue background for the whole page and orange background for the centered main content strip.

- -

Se ficou preso, pode sempre comparar o seu trabalho com o exemplo terminado no GitHub.

- -

Aqui, mal tocámos na superfície do CSS. Para saber mais, consulte o tópico de Aprender CSS.

- -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/elementar_de_javascript/index.html b/files/pt-pt/learn/comecar_com_a_web/elementar_de_javascript/index.html deleted file mode 100644 index fec3caaf51..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/elementar_de_javascript/index.html +++ /dev/null @@ -1,413 +0,0 @@ ---- -title: JavaScript - Essencial -slug: Learn/Comecar_com_a_Web/Elementar_de_JavaScript -tags: - - Aprender - - Beginner - - CodingScripting - - JavaScript - - Web - - 'l10n:priority' -translation_of: Learn/Getting_started_with_the_web/JavaScript_basics ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
- -
-

JavaScript é uma linguagem de programação que dá interatividade ao seu website (sob a forma, por exemplo, de jogos, respostas quando os botões são pressionados ou quando são inseridos dados nos formulários, estilos dinâmicos ou animações). Este artigo faz uma introdução a esta linguagem excitante e dá-lhe uma ideia do que é possível.

-
- -

O que é JavaScript, realmente?

- -

{{Glossary("JavaScript")}} (abreviado "JS") é uma {{Glossary("Dynamic programming language", "linguagem de programação dinâmica")}} completa que, quando é aplicada a um documento {{Glossary("HTML")}}, produz interatividade dinânimca no website. Foi inventada por Brendan Eich, co-fundador do projeto Mozilla, da Mozilla Foundation, e da Mozilla Corporation.

- -

JavaScript é incrivelmente versátil. Pode começar em ponto pequeno, com carrosséis, galerias de imagens, layouts flutuantes, e mensagens quando se prime um botão. Depois de ganhar experiência, será capaz de criar jogos, gráficos 2D e 3D animados, aplicações completas conduzidas por bases-de-dados e muito mais!

- -

JavaScript é relativamente compacta e muito flexível. Os programadores já escreveram uma grande variedade de ferramentas sobre o núcleo desta linguagem, o que abriu portas a uma vasta quantidade de funcionalidade extra com esforço mínimo. Isto inclui:

- - - -

Uma vez que este artigo é apenas uma introdução ligeira a JavaScript, não vamos confundi-lo com detalhes sobre a diferença entre JavaScript puro e as ferramentas enumeradas em cima. Poderá aprender esse detalhe mais tarde, na nossa área de aprendizagem de JavaScript, e no resto da MDN.

- -

De seguida vamos introduzi-lo a alguns aspetos do núcleo da linguagem (JS puro, sem ferramentas), e também vai jogar com algumas funcionalidades da API do navegador. Divirta-se!

- -

Um exemplo "olá mundo"

- -

A secção anterior deve parecer mesmo empolgante — JavaScript é uma das tecnologias web mais animadas, e à medida que se torna bom a usá-la, os seus sites entrarão numa nova dimensão de poder e creatividade.

- -

Contudo, ficar confortável com JavaScript é um pouco mais difícil do que ficar confortável com HTML e CSS. Terá que começar com projetos pequenos e prosseguir com passos pequenos e consistentes. Para começar, vamos mostrar como adicionar JavaScript básico à sua página, criando um exemplo "hello world" / "olá mundo!" (o padrão de exemplos básicos de programação).

- -
-

Importante: Se não tem seguido o resto deste curso, descarregue este exemplo de código e utilize-o como ponto de partida.

-
- -
    -
  1. Primeiro, crie uma pasta "scripts" (sem aspas) na raíz do seu site de testes. Depois, dento desta pasta, crie um ficheiro chamado main.js.
  2. -
  3. A seguir, no ficheiro index.html introduza o elemento seguinte numa linha nova mesmo antes da etiqueta de fechi </body>: -
    <script src="scripts/main.js"></script>
    -
  4. -
  5. Basicamente isto faz o mesmo que o elemento {{htmlelement("link")}} faz com CSS — aplica o código JavaScript à página, para que surta efeito no HTML (juntamente com o CSS, e outros recursos da página).
  6. -
  7. Agora adicione o código seguinte ao ficheiro main.js: -
    var myHeading = document.querySelector('h1');
    -myHeading.textContent = 'Olá mundo!';
    -
  8. -
  9. Finalmente, certifique-se que guardou as alterações aos ficheiros HTML e JavaScript, e carregue o ficheiro index.html no navegador. Deverá ver algo como:
  10. -
- -
-

Nota: O motivo pelo qual pusemos o elemento {{htmlelement("script")}} no fim do ficheiro HTML é que os elementos são carregados pelo navaegador na ordem em que aparecem no ficheiro. Se o JavaScript é carregado primeiro e tem que afetar o HTML por baixo dele, pode não funcionar, já que o código JavaScript seria carregado antes do HTML que era suposto modificar. Assim, colocar o JavaScript no fim do ficheiro HTML costuma ser a melhor estratégia.

-
- -

O que aconteceu?

- -

O texto do título foi mudado para "Hello world!", utilizando JavaScript. Isto foi feito com a função {{domxref("Document.querySelector", "querySelector()")}} para obter uma referência do título e guardá-la numa variável myHeading. Isto é semelhante ao que fizémos com seletores CSS. Quando se pretende fazer algo com um elemento, há que selecioná-lo primeiro.

- -

Depois, muda-se o valor da propriedade {{domxref("Node.textContent", "textContent")}} da variável myHeading (a qual representa o conteúdo textual do título) para "Olá Mundo!".

- -
-

Nota: Ambas as funções utilizadas fazem parte da API do Document Object Model (DOM) , o qual permite manipular documentos HTML.

-
- -

Curso intensivo das bases da linguagem

- -

Vamos explicar algumas funcionalidades fundamentais da linguagem JavaScript, para permitir uma melhor compreensão de como a mesma funciona. Note que estas funcionalidades são comuns a todas as linguagens de programação, por isso, se dominar estes fundamentos, estará no bom caminho para programar praticamente qualquer coisa!

- -
-

Importante: Neste artigo, tente introduzir os exemplos de código na consola JavaScript para ver o que acontece. Para mais detalhes sobre a consola JavaScript, veja o artigo Descobrir as ferramentas de desenvolvimentos do navegador.

-
- -

Variáveis

- -

{{Glossary("Variable", "Variáveis")}} são "recipientes" em que pode guardar valores. Comece por declarar a variável com a palavra-chave var, seguida de qualquer nome que lhe queira dar:

- -
var minhaVariavel;
- -
-

Nota: O ponto e vírgula indica onde termina a instrução; apenas é estritamente necessário quando pretende separar instruções numa só linha. Contudo, algumas pessoas acham que é boa prática colocar este sinal no fim de cada instrução. Há mais regras sobre quando se deve ou não utilizá-lo — veja o artigo Your Guide to Semicolons in JavaScript (inglês) para obter mais detalhes.

-
- -
-

Nota: O nome da varíavel pode ser quase tudo, mas há restrições (veja este artigo sobre regras para dar nome às variáveis (inglês)). Se não tem a certeza, pode verificar o nome da sua variável para assegurar que é válido.

-
- -
-

Nota: JavaScript é sensível a maiúsculas — minhaVariavel é uma variável diferente de minhavariavel. Se tiver encontrar problemas depois de escrever p código, verifique as maiúsculas e minúsculas!

-
- -

Depois de declarar a variável, pode atribuir-lhe um valor:

- -
minhaVariavel = 'Bob';
- -

Pode efetuar ambas as operações com uma só instrução:

- -
var myVariable = 'Bob';
- -

O valor é obtido simplesmente escrevendo o nome da variável:

- -
myVariable;
- -

Depois de lhe dar um valor, pode optar por mudá-lo mais tarde:

- -
var minhaVariavel = 'Bob';
-minhaVariavel = 'Steve';
- -

Atenção que as variáveis podem ter valores com diferentes tipos de de dados:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
VariávelExplicaçãoExemplo
{{Glossary("String")}}Uma sequência de texto conhecido como string ou cadeia de caracteres. Para indicar que é uma string, envolve-se em plicas '.var minhaVariavel = 'Bob';
{{Glossary("Number")}}Um número. Não tem plicas em sua volta.var minhaVariavel = 10;
{{Glossary("Boolean")}}Valor que ou é verdadeiro ou falso. As palavras true e false são palavras-chave em JS, e não precisam de plicas.var minhaVariavel = true;
{{Glossary("Array")}}Estrutura que permite guardar múltiplos valores numa só referência.var minhaVariavel = [1,'Bob','Steve',10];
- Cada elemento da Array é referido desta forma (começa em zero):
- myVariable[0], myVariable[1], etc.
{{Glossary("Object")}}Pode ser qualquer coisa. Em JavaScript, tudo é um objeto e pode guardar-se numa variável. Mantenha isto em mente enquanto aprende.var minhaVariavel = document.querySelector('h1');
- Assim como todos os exemplos anteriores.
- -

Então para que precisamos das variáveis? Bem, são necessárias para qualquer tarefa interessante em programação. Se não houvesse valores que mudassem, não seria possível criar nada que fosse dinâmico, como personalizar uma mensagem de boas vindas ou mudar a imagem que se está a ver numa galeria.

- -

Comentários

- -

Pode deixar comentários no seu código JavaScript, tal como em CSS:

- -
/*
-Tudo entre estas marcas é um comentário.
-*/
- -

Se o comentário não contiver quebras de linha, deve ser mais fácil utilizar duas barras, assim:

- -
// Isto é um comentário
-
- -

Operadores

- -

Um {{Glossary("operator")}} é um símbolo matemático que produz o resultado de uma operação entre dois valores (que podem ser variáveis). Na tabela seguinte constam alguns dos operadores mais simples, juntamente com alguns exemplos que pode experimentar na consola de JavaScript.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OperadorExplicaçãoSímbolo(s)Exemplo
AdiçãoSoma números ou junta duas strings.+6 + 9;
- "Hello " + "world!";
Subtração, Multiplicação, DivisãoComportam-se com esperado em aritmética.-, *, /9 - 3;
- 8 * 2; // em JS, o sinal de "vezes" é um asterisco
- 9 / 3;
AtribuiçãoJá vimos isto: atribui um valor a uma variável.=var minhaVariavel = 'Bob';
IgualdadeFaz um teste para verificar se dois valores são iguais e retorna um valor booleano (true/false).===var minhaVariavel = 3;
- minhaVariavel === 4;
Negação, DesigualdadeDevolve o valor logicamente oposto, ou seja, torna o verdadeiro em falso e vice-versa. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal.!, !== -

The basic expression is true, but the comparison returns false because we've negated it:

- -

var myVariable = 3;
- !(myVariable === 3);

- -

Verificar se "a minhaVariavel NÃO é igual a 3". Retorna false porque minhaVariavel é de facto igual a 3.

- -

var minhaVariavel = 3;
- minhaVariavel !== 3;

-
- -

Há muito mais operadores a explorar, mas por agora basta. Veja uma lista completa no artigo Expressões e operadores.

- -
-

Nota: Misturar tipos de dados pode ter resultados estranhos, então certifique-se que está a utilizar as variáveis corretamente e que os resultados estão dentro do esperado. Por exemplo, introduza "35" + "25" na consola. Porque é que não faz a soma dos números? Porque as aspas tornam os números em strings, então em vez de somar, fez a concatenção das strings. Se introduzir, 35 + 25 já obterá o resultado correto.

-
- -

Condições

- -

Condições são estruturas de código que permitem, em função do valor lógico (verdadeiro/falso) de uma expressão, executar código de entre várias alterantivas. Uma forma comum de uma condiçães é a instrução if ... else (se ... senão). Por exemplo:

- -
var gelado = 'chocolate';
-if (gelado === 'chocolate') {
-  alert('Viva, adoro gelado de chocolate!');
-} else {
-  alert('Ohhhh, mas o meu favorito é chocolate...');
-}
- -

A expressão dentro de parênteses em if ( ... ) é a condição — utilza o operador de igualdade (como foi descrito em cima) para comparar a variável gelado com a string 'chocolate' e assim verificar se são iguais. Caso esta comparação devolva true, é executado o primeiro bloco de código. Se não for verdadeira, não é executado o primeiro mas sim o segundo bloco de código, depois da instrução else.

- -

Funções

- -

{{Glossary("Function", "Functions")}} são uma maneira de juntar uma funcionalidade ou um conjunto instruções que se pretende reutilizar. Quando se pretende utilizar esta funcionalidade, chama-se a função pelo nome, em vez de voltar a escrever o código em cada utilização. Já pudémos ver a utilização de algumas funções, por exemplo:

- -
    -
  1. -
    var minhaVariavel = document.querySelector('h1');
    -
  2. -
  3. -
    alert('hello!');
    -
  4. -
- -

Estas funções, document.querySelector e alert, estão incluídas no navegador para serem utilizadas sempre que necessário.

- -

Quando vê algo que parece um nome de uma variável mas tem parênteses à direita— () —  é provavelmente uma função. As funções costumam possuir {{Glossary("Argument", "arguments")}} — dados de que necessitam para fazer o seu trabalho. Estes são passados dentros dos parênteses, separados por vírgulas quando há mais do que um.

- -

Por exemplo, a função alert() faz aparecer um "pop-up" na janela do navegador, mas é preciso dar-lhe uma string como argumento para que ela saiba o que escrever.

- -

E as boa notícia é que pode definir as suas próprias funções. Neste exemplo escrevemos uma função simples que aceita dois argumentos numéricos e multiplica-os:

- -
function multiplicar(num1,num2) {
-  var resultado = num1 * num2;
-  return resultado;
-}
- -

Tente declarar esta função na consola e depois testá-la com vários argumentos. Por exemplo:

- -
multiplicar(4, 7);
-multiplicar(20, 20);
-multiplicar(0.5, 3);
- -
-

Nota: A instrução return diz ao navegador para devolver/retornar a variável result para fora da função para que o seu valor possa ser utilizado. Isto é necessário porque variáveis definidas dentro das funções só estão disponíveis dentro dessas funções — a essa particularidade chama-se o âmbito da variável ({{Glossary("Scope", "scoping")}}). (Leia mais sobre âmbito de variáveis)

-
- -

Eventos

- -

Num site, interactividade a sério precisa de eventos. Eles são estruturas de código que esperam que algo aconteça no navegador e respondem executando código. O exemplo mais óbvio é o evento de clique, que é enviado pelo navegador quando se clica em algo com o rato. Para demonstrar, introduza isto na sua consola, e depois clique na página atual:

- -
document.querySelector('html').onclick = function() {
-    alert('Ai! Para de me picar!');
-}
- -

Há muitas maneiras de associar um evento a um elemento. Aqui, selecionamos o elemento {{htmlelement("html")}}, atribuímos à sua propriedade onclick o manuseador do evento (event handler), que neste caso é uma função anónima (sem nome), que contém o código que queremos que o evento de clique execute.

- -

Note que isto:

- -
document.querySelector('html').onclick = function() {};
- -

É equivalente a isto:

- -
var myHTML = document.querySelector('html');
-myHTML.onclick = function() {};
- -

Só que o primeiro é mais curto.

- -

Supercarregar o nosso site-exemplo

- -

Agora que que já vimos as bases de JavaScript, vamos acrescentar umas funcionalidades fixes ao nosso site para ver o que é possível.

- -

Acrescentar um alterador de imagens

- -

Nesta secção, vamos acrescentar uma imagem adicional ao nosso site com funções da API da DOM, utilizando JavaScript para mudar alternar entre as duas imagens quando se clica nelas.

- -
    -
  1. Primeiro, encontre outra imagem que goste de ter no seu site. Certifique-se que o tamanho é o mais próximo possível da primeira imagem.
  2. -
  3. Guarde-a na pasta images.
  4. -
  5. Mude o nome para "firefox2.png" (sem aspas).
  6. -
  7. Vá ao ficheiro main.js, e introduza o seguinte código JavaScript. (Apague o código do "olá mundo", se ainda lá estiver) -
    var myImage = document.querySelector('img');
    -
    -myImage.onclick = function() {
    -    var mySrc = myImage.getAttribute('src');
    -    if(mySrc === 'images/firefox-icon.png') {
    -      myImage.setAttribute('src','images/firefox2.png');
    -    } else {
    -      myImage.setAttribute('src','images/firefox-icon.png');
    -    }
    -}
    -
  8. -
  9. Guarde todos os ficheiros e carregue o index.html no navegador. Agora, quando clicar sobre a imagem, ela deve mudar para a outra!
  10. -
- -

Guardou-se uma referência para o elemento {{htmlelement("img")}} na variável myImage. Depois, atribui-se à propriedade onclick desta variável uma função anónima. Agora, sempre que se clica no elemento:

- -
    -
  1. Obtem-se o valor do atributo src.
  2. -
  3. Utiliza-se uma condição para averiguar se o valor do mesmo é igual ao caminho da primeira imagem: -
      -
    1. Se for, muda-se para o caminho da 2ª imagem, o que a obriga a ser carregada no elemento {{htmlelement("img")}}.
    2. -
    3. Se não for (e portanto, já se trocaram as imagens), o valor de src volta a ser o caminho da imagem original.
    4. -
    -
  4. -
- -

Dar uma mensagem de boas-vindas personalizada

- -

De seguida vamos acrescentar mais um pouco de código, que vai mudar o título da página para uma mensagem de boas-vindas personalizada quando o utilizador navega no site pela primeira vez. A mesma vai persistir, mesmo que o utilizador saia do site e volte mais tarde — vamos guardá-la com a API de Web Storage. Também vamos acrescentar opção de mudar de utilizador e, com o mesmo, a mensagem de boas-vindas sempre que for necessário.

- -
    -
  1. Em index.html, acrescente esta linha logo antes do elemento {{htmlelement("script")}}: - -
    <button>Change user</button>
    -
  2. -
  3. Em main.js, coloque o código seguinte no fim do ficheiro, tal como está escrito — isto obtem referências ao novo botão e o título, e guarda-os em variáveis: -
    var myButton = document.querySelector('button');
    -var myHeading = document.querySelector('h1');
    -
  4. -
  5. Agora acrescente a função em baixo para estabelecer a mensagem personalizada — por agora não faz nada, mas já vamos tratar disso: -
    function setUserName() {
    -  var myName = prompt('Por favor introuduza o seu nome.');
    -  localStorage.setItem('name', myName);
    -  myHeading.textContent = 'Mozilla is cool, ' + myName;
    -}
    - Este função faz uso da função prompt(), que mostra uma caixa de diálogo, semelhante a alert(). Mas a prompt() pede ao utilizador que introduza dados, que armazena numa variável depois que o mesmo faça OK. Neste caso, pedimos ao utilizador que introduza o seu nome. Depois, recorremos à API chamada localStorage, que nos permite guardar dados no navegador para os obter mais tarde. Utilizamos a função setItem() para criar e guardar o artigo 'name', e dando-lhe o valor da variável myName, a qual contém o nome introduzido pelo utilizador. Finalmente, mudamos o textContent do título para uma string, à qual concatenamos o nome recentemente armazenado.
  6. -
  7. Próximo: acrescente este bloco if ... else — podemos chamar-lhe código de iniciação, já que define a estrutura da aplicação quando é carregada pela primeira vez: -
    if(!localStorage.getItem('name')) {
    -  setUserName();
    -} else {
    -  var storedName = localStorage.getItem('name');
    -  myHeading.textContent = 'Mozilla is cool, ' + storedName;
    -}
    - Este bloco começa por utilizar o operador de negação ("não-lógico", representado pelo !) para averiguar se o dado name existe. Se não existir, a função setUserName() é utilizada para o criar. Se existe (ou seja, o utilizador introduziu-o numa visita anterior), recuperamos o nome armazenado com getItem() e mudamos textContent do título para a string, mais o nome do utilizador, da mesma forma que fizémos em setUserName().
  8. -
  9. Finalmente, coloque o manuseador do evento onclick no botão, como se mostra em baixo. Quando se clica no botão, é chamada a função setUserName(). Isto permite ao utilizador introduzir um novo nome, sempre que desejar, ao premir o botão: -
    myButton.onclick = function() {
    -  setUserName();
    -}
    -
    -
  10. -
- -

Agora, sempre que visitar o site, vai pedir-lhe o seu nome de utilizador, e depois mostrar a mensagem personalizada. Pode mudar o nome sempre que quiser ao premir o botão. Como bónus, já que o nome está guardado em localStorage (armazenamento local), persiste mesmo que o site seja fechado, e mantém a mensagem quando se voltar ao site!

- -

Conclusão

- -

Se seguiu as instruções neste artigo, o resultado final deve ser uma página semelhante à que vê na imagem em baixo (pode ver  a nossa versão aqui):

- -

- -

Caso se tenha perdido, pode comparar o código que escreveu com o nosso exemplo terminado no GitHub.

- -

Este artigo mal rasou a superfície de JavaScript. Se gostou de brincar e deseja continuar a aprender, dirija-se ao nosso tópico de aprendizegem de JavaScript.

- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/html_basicos/index.html b/files/pt-pt/learn/comecar_com_a_web/html_basicos/index.html deleted file mode 100644 index 4601e08092..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/html_basicos/index.html +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: HTML - Essencial -slug: Learn/Comecar_com_a_Web/HTML_basicos -tags: - - Aprender - - CodingScripting - - HTML - - Principiante - - Web - - 'l10n:priority' -translation_of: Learn/Getting_started_with_the_web/HTML_basics ---- -
-
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web")}}
- -
-

HTML (Linguagem de Marcação de Hipertexto) é o código que é utilizado para estruturar uma página da web e o seu conteúdo. Por exemplo, o conteúdo poderá ser estruturado dentro de um conjunto de parágrafos, uma lista de pontos com marcadores, ou utilizando imagens e tabelas de dados. Como o título sugere, este artigo irá dar-lhe uma compreensão básica do HTML e as suas funções.

-
- -

Então, o que é realmente o HTML?

- -

HTML não é uma linguagem de programação; é uma linguagem de marcação que define a estrutura do seu conteúdo. HTML consiste numa série de {{Glossary("element", "elementos")}}, que se utilizam para envolver, ou cercar, diferentes partes do conteúdo, e assim fazê-lo ter uma determinada aparência ou agir de determinada maneira. As {{Glossary("tag", "etiquetas")}} envolventes podem interligar as palavras ou imagens para outro lugar, colocar palavras em itálico, tornar a letra maior ou menor, e assim por diante. Por exemplo, veja a seguinte linha de conteúdo:

- -
O meu gato é muito rabugento
- -

Caso queiramos que a linha esteja separada de outras, podemos especificar que é um parágrafo envolvendo-a em etiquetas de parágrafo:

- -
<p>O meu gato é muito rabugento</p>
- -

Anatomia de um elemento HTML

- -

Vamos explorar este elemento de parágrafo um pouco mais.

- -

- -

As partes principais do nosso elemento são:

- -
    -
  1. A etiqueta de abertura: Consiste no nome do elemento (neste caso, p), envolto em parênteses angulares. Isto afirma onde começa o elemento, ou onde começa a ter efeito — neste caso, onde começa o parágrafo.
  2. -
  3. A etiqueta de fecho: É igual à de abertura, mas tem uma barra antes do nome do elemento. Isto afirma onde acaba o elemento — neste caso, onde fica o fim do parágrafo. Omitir a etiqueta de fecho é um erro de principiante comum e pode levar a resultados estranhos.
  4. -
  5. O conteúdo: É o conteúdo do elemento, que neste caso é só texto.
  6. -
  7. O elemento: A etiqueta de abertura, mais a etiqueta de fecho, mais o conteúdo, é igual ao elemento.
  8. -
- -

Elementos também podem ter atributos, que se parecem assim:

- -

- -

Atributos contêm informação extra sobre o elemento que não quer que apareça no conteúdo. Aqui, class é o nome do atributo, e editor-note é o valor do atributo. O atributo class permite identificar o elemento como sendo parte de um grupo, que pode ser alvo de regras CSS e outras coisas.

- -

Um atributo deverá ter sempre:

- -
    -
  1. Um espaço entre si o nome do elemento (ou do atributo anterior, se esse elemento já possuir um ou mais atributos).
  2. -
  3. O nome do atributo, seguido de um sinal de igual.
  4. -
  5. O valor do atributo, envolto em abre e fecha aspas.
  6. -
- -
-

Nota: Valores de atributos que não possuam espaço em branco ASCII (ou nenhum dos caracteres " ' = < >), mas recomendado que todos os valores de atributos sejam envoltos em aspas, para tornar o código mais consistente e compreensível.

-
- -

Aninhar elementos

- -

Também pode colocar elementos dentro de outros elementos  — chama-se a isto aninhar. Se quisermos declarar que o nosso gato é muito rabugento, podemos cercar a palavra "muito" com um elemento {{htmlelement("strong")}}, que significa que a palavra tem ênfase forte:

- -
<p>O meu gato é <strong>muito</strong> rabugento.</p>
- -

No entanto, tem que se certificar que os seus elementos estão devidamente aninhados: no exemplo em cima, abrimos o elemento {{htmlelement("p")}} primeiro, e depois o elemento {{htmlelement("strong")}} , portanto temos que fechar o elemento {{htmlelement("strong")}} primeiro, e só depois o {{htmlelement("p")}}. A linha seguinte está errada:

- -
<p>O meu gato é <strong>muito rabugento.</p></strong>
- -

Os elementos têm que abrir e fechar corretamente para que seja claro se estão dentro ou fora uns dos outros. Se ficarem sobrepostos como se mostrou em cima, o seu navegador vai tentar adivinhar o que quis dizer, e pode obter resultados inesperados. Então, não faça isso!

- -

Elementos vazios

- -

Alguns elementos não têm conteúdo, aos quais chamamos elementos vazios. Veja o elemento {{htmlelement("img")}} que já temos no nosso HTML:

- -
<img src="images/firefox-icon.png" alt="My test image">
- -

O mesmo contém dois atributos, mas não há etiqueta de fecho, </img>, nem conteúdo no seu interior, uma vez que um elemento de imagem não envolve conteúdo para o afetar. O seu propósito é incorporar uma imagem na página HTML, no local onde aparece.

- -

Anatomia de um documento HTML

- -

Assim terminamos as bases de elementos HTML individuais, mas eles não são muito úteis sozinhos. Vamos agora ver como os elementos se combinam para formar uma página HTML inteira. Voltemos ao código que escrevemos no ficheiro de exemplo index.html (que conhecemos no artigo Lidar com ficheiros):

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-    <title>My test page</title>
-  </head>
-  <body>
-    <img src="images/firefox-icon.png" alt="My test image">
-  </body>
-</html>
- -

Aqui temos:

-
- - - -

Imagens

- -

Vamos virar a nossa atenção para o elemento {{htmlelement("img")}} outra vez:

- -
<img src="images/firefox-icon.png" alt="My test image">
- -

Como já referimos, incorpora uma imagem na nossa página, no local onde aparece. Para tal recorre ao atributo src (source — fonte, origem), que contém o caminho para o ficheiro de imagem.

- -

Também incluímos o atributo alt (alternativa). Neste atributo, você especifica texto descritivo para utilizadores que não conseguem ver a imagem, possivelmente porque:

- -
    -
  1. Têm deficiências visuais. Utilizadores com deficiências visuais significativas costumam utilizar ferramentas chamadas leitores de ecrã que lhes lê o texto alternativo.
  2. -
  3. Alguma coisa correu mal e fez com que a imagem não fosse mostrada. Por exemplo, tente mudar deliberadamente o caminho no atributo src para torná-lo incorreto. Se guardar e recarregar a página, deve ver algo como isto em vez da imagem:
  4. -
- -

- -

As palavras-chave sobre texto alternativo são: "texto descritivo". Ou seja, deve dar ao leitor informação suficiente para ter uma boa ideia do que a imagem transmite. Neste exemplo, o texto atual, "My test image" não é nada bom. Uma alternativa muito melhor para o nosso logótipo do Firefox seria "Logótipo do Firefox: uma raposa flamejante a rodear o mundo."

- -

Agora, tenta encontrar texto alternativo melhor para a tua imagem.

- -
-

Nota: saiba mais sobre acessibilidade em MDN - Página de Acessibilidade.

-
- -

Marcação de texto

- -

Esta secção irá abranger alguns dos elementos básicos de HTML que irá utilizar para marcar texto.

- -

Títulos

- -

Elementos de título permitem especificar que determinadas partes do seu conteúdo são títulos (ou subtítulos) do conteúdo. Da mesma forma que um livro tem um título principal, títulos de capítulos e subtítulos, um documento HTML também os pode ter. HTML contém seis níveis de títulos, {{htmlelement("h1")}}–{{htmlelement("h6")}} mas geralmente usam-se no máximo 3 ou 4:

- -
<h1>Título principal</h1>
-<h2>Título mais abrangente</h2>
-<h3>Subtítulo</h3>
-<h4>Sub-subtítulo</h4>
- -

Tente agora acrescentar um título à sua página HTML mesmo por cima do seu elemento {{htmlelement("img")}}.

- -

Parágrafos

- -

Como já foi explicado, elementos {{htmlelement("p")}} servem para conter parágrafos; vai usá-los frequentemente quando marcar conteúdo textual:

- -
<p>Isto é um único parágrafo</p>
- -

Acrescente um ou mais parágrafos com a sua amostra de texto (conforme o artigo Qual será a aparência do seu site da Web?), diretamente por baixo do elemento {{htmlelement("img")}}.

- -

Listas

- -

Grande parte do conteúdo da web está em listas, e HTML tem elementos especiais para as mesmas. Marcar listas consiste sempre em pelo menos 2 elementos. As listas mais comuns são as listas ordenadas e não ordenadas:

- -
    -
  1. Listas não ordenadas são listas em que a ordem dos elementos não é relevante, como uma lista de compras. São envoltas no elemento {{htmlelement("ul")}}.
  2. -
  3. Listas ordenadas são listas em que a ordem dos elementos é importante, como uma receita. São envoltas no elemento {{htmlelement("ol")}}.
  4. -
- -

Cada artigo na lista é colocado dentro de um elemento {{htmlelement("li")}} (list item).

- -

Por exemplo, se quisermos transformar parte deste trecho numa lista:

- -
<p>Na Mozilla, somos uma comunidade global de tecnólogos, pensadores, e construtores que trabalham juntos ... </p>
- -

Podemos modificar a marcação desta forma:

- -
<p>Na Mozilla, somos uma comunidade global de</p>
-
-<ul>
-  <li>tecnólogos</li>
-  <li>pensadores</li>
-  <li>construtores</li>
-</ul>
-
-<p>que trabalham juntos ... </p>
- -

Tente acrescentar uma lista ordenada ou não ordenada à sua página de exemplo.

- -

Hiperligações

- -

As hiperligações são muito importantes — são elas que tornam a internet na internet! Para acrescentar uma ligação, precisamos de um elemento simples — {{htmlelement("a")}} — cujo "a" abrevia "âncora". Para transformar texto no seu parágrafo numa ligação, siga estes passos:

- -
    -
  1. Escolha algum texto. Escolhemos o texto "Manifesto da Mozilla".
  2. -
  3. Envolva o texto num elemento {{htmlelement("a")}}, assim: -
    <a>Manifesto da Mozilla</a>
    -
  4. -
  5. Dê ao elemento {{htmlelement("a")}} um atributo href, assim: -
    <a href="">Manifesto da Mozilla</a>
    -
  6. -
  7. Preencha o valor deste atributo com o endereço web para o qual quer ligar a hiperligação: -
    <a href="https://www.mozilla.org/pt-PT/about/manifesto/">Manifesto da Mozilla</a>
    -
  8. -
- -

Pode obter resultados inesperados se omitir a parte do protocolo no início do endereço web (https:// ou http://). Depois de criar uma hiperligação, clique para assegurar que está a enviá-lo para onde é pretendido.

- -
-

href pode, à primeira vista, parecer uma escolha obscura para o nome de um atributo. Se tiver dificuldades em lembrar-se dele, recorde que significa hypertext reference.

-
- -

Agora, acrescente a hiperligação à sua página, se ainda não o fez.

- -

Conclusão

- -

Se seguiu todas as instruções nesta página, deve ter conseguido uma página que se assemelha à página em baixo (também pode vê-la aqui):
-
- A web page screenshot showing a firefox logo, a heading saying mozilla is cool, and two paragraphs of filler text

- -

Se ficou preso, pode comparar o seu trabalho com o exemplo do código terminado no GitHub.

- -

Aqui, mal tocámos na superfície da linguagem HTML. Para descobrir mais, dirija-se ao nosso tópico sobre Aprender HTML.

- -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Lidar_com_ficheiros","Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/index.html b/files/pt-pt/learn/comecar_com_a_web/index.html deleted file mode 100644 index 59a4431592..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Primeiros passos na Web -slug: Learn/Comecar_com_a_Web -tags: - - Beginner - - CSS - - Desenho - - Guía - - HTML - - 'I10n:priority' - - Index - - publicação - - teoria -translation_of: Learn/Getting_started_with_the_web ---- -
{{LearnSidebar}}
- -
-

Iniciação à Web é uma série concisa introduzindo-lhe os aspetos práticos do desenvolvimento da Web. Irá configurar as ferramentas necessárias para criar uma página da Web simples e publicar o seu próprio código simples.

-
- -

A história do seu primeiro site da Web

- -

É muito trabalho para criar um site da Web profissional, por isso, se é novo no desenvolvimento da Web, nós encorajamos que comece por uma coisa pequena. Não irá criar outro Facebook de imediato, mas não é difícil ter o seu próprio site da Web simples on-line. Vamos lá começar.

- -

Ao trabalhar com os artigos listados abaixo em ordem, irá passar do nada para ter a sua primeira página da Web on-line. Vamos lá!

- -

Instalar software básico

- -

Quando se trata de ferramentas para criar um site da Web, há muito a escolher. Se está apenas a começar, pode ficar confuso com a variedade de editores de código, estruturas e ferramentas de teste disponíveis. Em Instalar software básico, nós mostramos-lhe passo-a-passo como instalar apenas o software necessário para iniciar um desenvolvimento da web básico.

- -

Qual será a aparência do seu site da Web?

- -

Antes de começar a escrever o código do seu site da Web, deverá planeá-lo primeiro. Que informação está a apresentar? Que tipo de letra e cores está a utilizar? Como é que será apresentado o seu site da Web? Nós descrevemos um método simples que pode seguir para planear o conteúdo e o desenho do seu site.

- -

Lidar com ficheiros

- -

Um site consiste em muitos ficheiros: conteúdo de texto, código, stylesheets, conteúdo de média, e mais. Quando constrói um site, precisa de organizar os seus ficheiros e certificar-se que podem comunicar uns com os outros. Lidar com ficheiros explica como criar uma estrutura para os ficheiros do seu site e quais as questões que devem ser do seu conhecimento.

- -

Básicos de HTML

- -

Hypertext Markup Language (HTML) é o código que usa para estruturar, dar significado, e propósito ao seu conteúdo de web. Por exemplo, é o meu conteúdo um conjunto de parágrafos, ou uma lista de pontos? Tenho imagens inseridas na minha página? O HTML - Essencial fornece informação suficiente para o familiarizar com o HTML, sem o sobrecarregar.

- -

Básicos de CSS

- -

Cascading Stylesheets (CSS) é o código que usa para decorar o seu site. Por exemplo, quer o texto colorido negro ou vermelho? Onde desenhar o conteúdo no ecrã? Que imagens de fundo e cores deve usar para decorar o site? CSS - Essencial leva-o através do que precisa para começar.

- -

Básicos de JavaScript

- -

JavaScript é a linguagem de programação que utiliza para adicionar funcionalidades interativas ao seu website, por exemplo, jogos, coisas que acontecem quando botões são premidos ou quando dados são introduzidos em formulários, efeitos de estilo dinâmicos, animação, e muito mais. JavaScript - Essencial dá-lhe uma ideia do que é possível com esta linguagem emocionante, e como começar.

- -

Publicar o seu site da Web

- -

Após de escrever o código e organizar os ficheiros que compõem o seu site, tem de o colocar online para que as pessoas o possam encontrar. "Publicar o seu site da Web" descreve como colocar o seu código de amostra simples online com o mínimo de esforço.

- -

Como é que funciona a Web

- -

Quando acede ao seu site favorito, muitas coisas complicadas acontecem em segundo plano de que poderá não ter conhecimento. Como funciona a Web descreve o que acontece quando visualiza uma página da web no seu computador.

- -

Consulte também

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/installing_basic_software/index.html b/files/pt-pt/learn/comecar_com_a_web/installing_basic_software/index.html deleted file mode 100644 index ebc5ddd3e3..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/installing_basic_software/index.html +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Instalar software básico -slug: Learn/Comecar_com_a_Web/Installing_basic_software -tags: - - Aprender - - Beginner - - Configurar - - Ferramentas - - Mecânicas da Web - - Navegador - - editor de texto - - 'l10n:priority' -translation_of: Learn/Getting_started_with_the_web/Installing_basic_software ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web")}}
- -
-

Neste artigo, mostramos-lhe de que ferramentas precisa para desenvolvimento da Web básico, e como instalá-las corretamente.

-
- -

Que ferramentas é que os profissionais utilizam?

- - - -

De que ferramentas realmente preciso, de momento?

- -

Parece uma lista assustadora, mas felizmente pode começar a desenvolver para a web sem saber nada sobre a maioria daquelas coisas. Neste artigo instalamos o mínimo dos mínimos — editor de texto e navegadores modernos.

- -

Instalar um editor de texto

- -

Provavelmente já tem um editor de texto simples no seu computador. O Windows inclui, de fábrica, o Bloco de Notas (Notepad) e o macOS vem com o Editor de Texto (TextEdit). Em distribuições de Linux, varia; Ubuntu vem com o gedit.

- -

Para desenvolvimento na Web, há alternativas mais completas que o Notepad ou TextEdit. Propomos-lhe começar com o Visual Studio Code, um editor gratuito que oferece pré-visualização em tempo real e sugestões de código.

- -
-

Não confundir Notepad (Bloco de Notas) com Wordpad! Este último é equiparável a programas de Office, que não são adequados para escrever código de computador, como já foi referido. 

-
- -

Instalar navegadores da Web modernos

- -

Antes de avançar, deve escolher uns navegadores que possa ter à mão para realizar testes. Escolha o seu sistema operativo e faça clique nos links para descarregar o programa de instalação respetivo dos seus navegadores preferidos:

- - - -
-

Internet Explorer (IE) não é compatível com funções da web modernas e pode não conseguir correr o seu projeto. Tipicamente não será necessário fazer os seus projetos compatíveis com o IE, pois muito poucas pessoas ainda a utilizam - certamente não se preocupe muito com isso enquanto está a aprender. Por vezes pode deparar-se com um projeto que requer apoio para o mesmo.

-
- -

Instalar um servidor da Web local

- -

Alguns exemplos terão de ser executados através de um servidor da Web para funcionar com sucesso. Pode aprender como fazer isto no artigo como configurar um servidor local de testes?

- -
{{NextMenu("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web")}}
- -

Neste módulo

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/comecar_com_a_web/lidar_com_ficheiros/index.html b/files/pt-pt/learn/comecar_com_a_web/lidar_com_ficheiros/index.html deleted file mode 100644 index 6489964938..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/lidar_com_ficheiros/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Lidar com ficheiros -slug: Learn/Comecar_com_a_Web/Lidar_com_ficheiros -tags: - - Beginner - - Ficheiros - - Guía - - HTML - - Programação Scripting - - 'l10n:priority' - - site da Web - - teoria -translation_of: Learn/Getting_started_with_the_web/Dealing_with_files ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web")}}
- -
-

Um site da internet consiste em muitos ficheiros: conteúdo de texto, código, folhas de estilo, conteúdo de multimédia, e assim por diante. Enquanto estiver a criar o site, tem que reunir esses ficheiros numa estrutura conveniente no seu computador local, certificar-se que os mesmos podem comunicar uns com os outros e preparar a apresentação do seu conteúdo, antes de eventualmente enviar os ficheiros para um servidor. Este artigo, Lidar com ficheiros, apresenta algumas questões de que deverá estar ciente para poder configurar uma estrutura de ficheiros conveniente para o seu site.

-
- -

Onde deve ficar o seu site no seu computador ?

- -

Quando estiver a trabalhar num site localmente, no seu computador, deve manter todos os ficheiros relacionados numa única pasta que seja o reflexo da estrutura de ficheiros do site no servidor. Esta pasta pode ficar onde quiser, mas deve colocá-la num local de fácil acesso: talvez no seu Ambiente de Trabalho, a pasta do seu utilizador, ou a raiz do seu disco rígido.

- -
    -
  1. Escolha um sítio para guardar os seus projetos relacionados com sites. Lá, crie uma pasta com o nome projetos-web (ou um nome semelhante). É aqui que vão morar todos os seus projetos de sites.
  2. -
  3. Dentro desta pasta, crie outra pasta para guardar o seu primeiro site. Pode-lhe chamar site-de-teste (ou algo mais criativo).
  4. -
- -

Um aparte sobre nomes de pastas e ficheiros

- -

Ao longo deste artigo poderá notar que os nomes que são dados às pastas e aos ficheiros estão todos em minúsculas e sem espaços. Isto porque:

- -
    -
  1. Muitos computadores, particularmente servidores da internet, são sensíveis a maiúsculas. Por exemplo, se criar um ficheiro de imagem com o nome site-de-teste/MinhaImagem.jpg e depois noutro ficheiro tentar referir-se a ela com o nome site-de-teste/minhaimagem.jpg, pode não resultar.
  2. -
  3. Navegadores, servidores, e linguagens de programação não tratam os espaços da mesma forma. Por exemplo, se usar espaços no nome do ficheiro, alguns sistemas podem tratá-lo como dois nomes separados. Alguns servidores substituem os espaços por "%20" (código de carácter de espaços em URI), e assim arruínam os seus links.
  4. -
- -

Por essas razões, é melhor habituar-se a escrever os nomes de pastas e ficheiros sem espaços e com palavras separadas por hífen, pelo menos até saber o que está a fazer. Desta forma, irá encontrar menos problemas mais tarde.

- -

Inicialmente, é melhor separar palavras com hífen em vez de underscoremeu-ficheiro.html em vez de meu_ficheiro.html, pois o motor de pesquisa Google interpreta o hífen como separador de palavras, mas não o underscore.

- -

Que estrutura deverá ter o seu site?

- -

De seguida, vamos discutir a estrutura que deve ter o site de teste. As coisas mais comuns que temos em qualquer site são um ficheiro índice e pastas que organizam os ficheiros por tipo: imagens, folhas de estilo e scripts. Vamos criá-las agora:

- -
    -
  1. index.html: Este ficheiro geralmente descreve o conteúdo da sua página principal, ou seja, o texto e imagens que as pessoas veem quando visitam o site pela primeira vez. Com um editor de texto, crie um ficheiro index.html e guarde-o dentro da pasta site-de-teste.
  2. -
  3. Pasta images: Esta pasta irá conter todas as imagens do seu site. Crie um pasta com este nome dentro da pasta site-de-teste.
  4. -
  5. Pasta styles: Esta pasta contém o código CSS que dá estilo ao conteúdo (por exemplo, cor do texto e do fundo). Crie-a dentro da pasta site-de-teste.
  6. -
  7. Pasta scripts: Esta pasta contém o código JavaScript que dá interatividade ao seu site (ex: botões que carregam dados quando premidos). Crie-adentro da pasta site-de-teste.
  8. -
- -
-

Nota: Em computadores com Windows, pode ter dificuldade em ver nomes dos ficheiros, porque no Windows tem uma opção, ligada por omissão, para Esconder extensões de ficheiros conhecidas. Em geral, pode desligá-la no Explorador do Windows, selecionar Opções de pastas..., desmarcar a opção em questão, na caixa de seleção, e clicar OK. Para mais informações sobre a sua versão específica de Windows, faça uma pesquisa na internet. 

-
- -

Caminhos de ficheiros

- -

Para permitir a comunicação entre ficheiros, é necessário estabelecer os caminhos entre eles. Para demonstrar, vamos inserir algum HTML no ficheiro index.html que mostra a imagem que escolheu no artigo Qual será a aparência do meu site?

- -
    -
  1. Copie a imagem escolhida para a pasta images.
  2. -
  3. Abra o ficheiro index.html, e copie o código exatamente como se mostra em baixo. Para já não se preocupe com o que significa — vamos olhar para estas estruturas mais tarde. -
    <!DOCTYPE html>
    -<html>
    -  <head>
    -    <meta charset="utf-8">
    -    <title>My test page</title>
    -  </head>
    -  <body>
    -    <img src="" alt="My test image">
    -  </body>
    -</html> 
    -
  4. -
  5. A linha <img src="" alt="My test image"> é o código HTML que insere uma imagem na página. É necessário dizer, neste trecho de código HTML, onde está a imagem. A mesma está dentro da diretoria images, a qual está na mesma diretoria que index.html. Para descer na estrutura de ficheiros, de index.html para a imagem, o caminho é images/nome-da-imagem. Por exemplo, se a mesma e chamasse firefox-icon.png, o caminho seria images/firefox-icon.png.
  6. -
  7. Insira este caminho no código HTML, entre as aspas neste trecho de código: src="".
  8. -
  9. Guarde o ficheiro HTML, depois carregue-o no seu navegador (com duplo clique). Deve conseguir ver o novo site, com a imagem! 
  10. -
- -

A screenshot of our basic website showing just the firefox logo - a flaming fox wrapping the world

- -

Algumas regras gerais sobre caminhos de ficheiros:

- - - -

Por agora é tudo o que precisa de saber.

- -
-

Nota: O Windows usa barras invertidas, como no caminho C:\windows. Mas em HTML, isso é irrelevante — mesmo que esteja a construir o site num sistema Windows, pode usar a barra normal, /.

-
- -

Que mais deverá ser feito?

- -

Por agora é tudo. A sua estrutura deverá ser como esta:

- -

A file structure in mac os x finder, showing an images folder with an image in, empty scripts and styles folders, and an index.html file

- -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/publicar_o_seu_site_da_web/index.html b/files/pt-pt/learn/comecar_com_a_web/publicar_o_seu_site_da_web/index.html deleted file mode 100644 index 7e99504b95..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/publicar_o_seu_site_da_web/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Publicar o seu site na Web -slug: Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web -tags: - - Aprender - - Beginner - - CodingScripting - - FTP - - GitHub - - Google App Engine - - Servidor de Web - - Web - - publicar -translation_of: Learn/Getting_started_with_the_web/Publishing_your_website ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web/Como_funciona_a_Web", "Learn/Comecar_com_a_Web")}}
- -
-

Assim que terminar de escrever o código e organizar os ficheiros que compõem o seu sire da web, precisa de colocar tudo online para que pessoas o possam encontrar. Este artigo explica como colocar o seu código de amostra online com pouco esforço.

-
- -

Quais são as opções?

- -

A publicação de um site na web é um tema complexo porque há muitas maneiras de o abordar. Este artigo não tenta documentar todos os métodos possíveis. Em vez disso, explica as vantagens e desvantagens de três abordagens que são práticas para os principiantes. Depois, passa por um método que pode funcionar de imediato para muitos leitores.

- -

Encontrar hospedagem na web e um nome de domínio

- -

Para ter mais controlo sob o conteúdo e a aparência dum site, a maioria das pessoas escolhe comprar hospedagem na web e um nome de domínio:

- - - -

Muitos sites profissionais escolhem este modo para pôr o seu site online.

- -

Além disso, precisará de um programa {{Glossary("FTP", "File Transfer Protocol (FTP)")}} (ver How much does it cost: software para mais detalhes) para transferir os ficheiros do site para o servidor. Os programas FTP variam muito, mas geralmente, tem de se ligar ao seu servidor web utilizando os detalhes fornecidos pela sua empresa de hospedagem (normalmente nome de utilizador, palavra-passe, nome de anfitrião). Depois, o programa mostra-lhe os seus ficheiros locais e os ficheiros do servidor web em duas janelas, e fornece-lhe uma forma de transferir ficheiros para trás e para a frente.

- -

- -

Dicas para encontrar hospedagem na web e um nome de domínio

- - - -

Usar uma ferramenta online

- -

Algumas ferramentas permitem publicar o seu site online:

- - - -

Estas opções são tipicamente grátis, mas é possível você acabar por precisar mais que as funções que elas oferecem.

- -

Usar um IDE online

- -

Existem várias aplicações web que imitam um ambiente de desenvolvimento de website, permitindo-lhe introduzir HTML, CSS e JavaScript, e depois mostrar o resultado desse código como um website — tudo num único separador do navegador. Em geral, estas ferramentas são relativamente fáceis de manusear, ótimas para aprender, boas para partilhar código (por exemplo, se quiser partilhar uma técnica com ou pedir ajuda de depuração a colegas num escritório diferente), e gratuitas (para funcionalidades básicas). Hospedam a sua página num endereço da web único. No entanto, as funcionalidades são limitadas, e estas aplicações normalmente não fornecem espaço de alojamento para ativos (como imagens).

- -

Experimente usar as seguintes IDEs para descobrir qual é a melhor para si:

- - - -

- -

Publicar via GitHub

- -

Agora vejamos como facilmente publicar o seu site através do GitHub Pages.

- -
    -
  1. Primeiro, inscreva se no GitHub e confirme o seu endereço eletrónico.
  2. -
  3. A seguir, a crie um repositório para guardar os seus ficheiros.
  4. -
  5. Nesta página, na caixa Repository name, escreva username.github.io, onde username é o seu nome de utilizador. Por exemplo, Bob Smith iria introduzir bobsmith.github.io na caixa. Selecione a caixa "Initialize this repository with a README", e carregue "Create repository".
  6. -
  7. Arraste os conteúdos da sua pasta para o website, para dentro do repositório. Depois carregue em Commit changes.
    - -
    -

    Nota: Certifique se que a sua pasta contém o ficheiro index.html.

    -
    -
  8. -
  9. -

    Navegue no seu navegador até username.github.io para ver o seu website online. Por exemplo, para o nome de utilizador chrisdavidmills, vai a chrisdavidmills.github.io.

    - -
    -

    Nota: Pode demorar alguns minutos para que o seu site esteja live. Se o seu site não for visível imediatamente, espere por uns minutos e tente novamente.

    -
    -
  10. -
- -

Para aprender mais, veja GitHub Pages Help.

- -

Leitura complementar

- - - -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web/Como_funciona_a_Web", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html b/files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html new file mode 100644 index 0000000000..d2ba60f9a3 --- /dev/null +++ b/files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html @@ -0,0 +1,100 @@ +--- +title: Como funciona Internet? +slug: Learn/Questoes_comuns/Como_funciona_a_Internet +tags: + - Mecânica da Web + - Principiante + - Tutorial +translation_of: Learn/Common_questions/How_does_the_Internet_work +--- +
{{LearnSidebar}}
+ +
+

This article discusses what the Internet is and how it works.

+
+ + + + + + + + + + + + +
Prerequisites:None, but we encourage you to read the Article on setting project goals first
Objective:You will learn the basics of the technical infrastructure of the Web and the difference between Internet and the Web.
+ +

Resumo

+ +

The Internet is the backbone of the Web, the technical infrastructure that makes the Web possible. At its most basic, the Internet is a large network of computers which communicate all together.

+ +

The history of the Internet is somewhat obscure. It began in the 1960s as a US-army-funded research project, then evolved into a public infrastructure in the 1980s with the support of many public universities and private companies. The various technologies that support the Internet have evolved over time, but the way it works hasn't changed that much: Internet is a way to connect computers all together and ensure that, whatever happens, they find a way to stay connected.

+ +

Active Learning

+ + + +

Deeper dive

+ +

A simple network

+ +

When two computers need to communicate, you have to link them, either physically (usually with an Ethernet cable) or wirelessly (for example with WiFi or Bluetooth systems). All modern computers can sustain any of those connections.

+ +
+

Note: For the rest of this article, we will only talk about physical cables, but wireless networks work the same.

+
+ +

Two computers linked together

+ +

Such a network is not limited to two computers. You can connect as many computers as you wish. But it gets complicated quickly. If you're trying to connect, say, ten computers, you need 45 cables, with nine plugs per computer!

+ +

Ten computers all together

+ +

To solve this problem, each computer on a network is connected to a special tiny computer called a router. This router has only one job: like a signaler at a railway station, it makes sure that a message sent from a given computer arrives at the right destination computer. To send a message to computer B, computer A must send the message to the router, which in turn forwards the message to computer B and makes sure the message is not delivered to computer C.

+ +

Once we add a router to the system, our network of 10 computers only requires 10 cables: a single plug for each computer and a router with 10 plugs.

+ +

Ten computers with a router

+ +

A rede das redes

+ +

So far so good. But what about connecting hundreds, thousands, billions of computers? Of course a single router can't scale that far, but, if you read carefully, we said that a router is a computer like any other, so what keeps us from connecting two routers together? Nothing, so let's do that.

+ +

Two routers linked together

+ +

By connecting computers to routers, then routers to routers, we are able to scale infinitely.

+ +

Routers linked to routers

+ +

Such a network comes very close to what we call the Internet, but we're missing something. We built that network for our own purposes. There are other networks out there: your friends, your neighbors, anyone can have their own network of computers. But it's not really possible to set cables up between your house and the rest of the world, so how can you handle this? Well, there are already cables linked to your house, for example, electric power and telephone. The telephone infrastructure already connects your house with anyone in the world so it is the perfect wire we need. To connect our network to the telephone infrastructure, we need a special piece of equipment called a modem. This modem turns the information from our network into information manageable by the telephone infrastructure and vice versa.

+ +

A router linked to a modem

+ +

So we are connected to the telephone infrastructure. The next step is to send the messages from our network to the network we want to reach. To do that, we will connect our network to an Internet Service Provider (ISP). An ISP is a company that manages some special routers that are all linked together and can also access other ISPs' routers. So the message from our network is carried through the network of ISP networks to the destination network. The Internet consists of this whole infrastructure of networks.

+ +

Full Internet stack

+ +

Encontrar computadores

+ +

If you want to send a message to a computer, you have to specify which one. Thus any computer linked to a network has a unique address that identifies it, called an "IP address" (where IP stands for Internet Protocol). It's an address made of a series of four numbers separated by dots, for example: 192.168.2.10.

+ +

That's perfectly fine for computers, but we human beings have a hard time remembering that sort of address. To make things easier, we can alias an IP address with a human readable name called a domain name. For example (at the time of writing; IP addresses can change) google.com is the domain name used on top of the IP address 173.194.121.32. So using the domain name is the easiest way for us to reach a computer over the Internet.

+ +

Show how a domain name can alias an IP address

+ +

Internet e a Web

+ +

As you might notice, when we browse the Web with a Web browser, we usually use the domain name to reach a website. Does that mean the Internet and the Web are the same thing? It's not that simple. As we saw, the Internet is a technical infrastructure which allows billions of computers to be connected all together. Among those computers, some computers (called Web servers) can send messages intelligible to web browsers. The Internet is an infrastructure, whereas the Web is a service built on top of the infrastructure. It is worth noting there are several other services built on top of the Internet, such as email and {{Glossary("IRC")}}.

+ +

Passos seguintes

+ + diff --git a/files/pt-pt/learn/common_questions/index.html b/files/pt-pt/learn/common_questions/index.html new file mode 100644 index 0000000000..62deec5d05 --- /dev/null +++ b/files/pt-pt/learn/common_questions/index.html @@ -0,0 +1,131 @@ +--- +title: Questões Comuns +slug: Learn/Questoes_comuns +translation_of: Learn/Common_questions +--- +
{{LearnSidebar}}
+ +

This section of the Learning Area is designed to provide answers to common questions that may come up, which are not necessarily part of the structured core learning pathways (e.g. the HTML or CSS learning articles.) These articles are designed to work on their own.

+ +

Como é que a Web funciona

+ +

This section covers web mechanics —questions relating to general knowledge of the Web ecosystem and how it works.

+ +
+
+

Como é que a Internet funciona?

+
+
The Internet is the backbone of the Web, the technical infrastructure that makes the Web possible. At its most basic, the Internet is a large network of computers which communicate all together. This article discusses how it works, at a basic level.
+
+

Qual é a diferença entre página da Web, site da Web, servidor da Web, e motor de pesquisa?

+
+
In this article we describe various web-related concepts: webpages, websites, web servers, and search engines. These terms are often confused by newcomers to the Web, or are incorrectly used. Let's learn what they each mean!
+
+

O que é um URL?

+
+
With {{Glossary("Hypertext")}} and {{Glossary("HTTP")}}, URL is one of the key concepts of the Web. It is the mechanism used by {{Glossary("Browser","browsers")}} to retrieve any published resource on the web.
+
+

O que é um nome de domínio?

+
+
Domain names are a key part of the Internet infrastructure. They provide a human-readable address for any web server available on the Internet.
+
+

O que é um servidor da Web?

+
+
The term "Web server" can refer to the hardware or software that serves web sites to clients across the Web — or both of them working together. In this article we go over how web servers work, and why they're important.
+
+

O que são hiperligações?

+
+
In this article, we'll go over what hyperlinks are and why they matter.
+
+ +

Ferramentas e configuração

+ +

Questions related to the tools/software you can use to build websites.

+ +
+
+

How much does it cost to do something on the Web?

+
+
When you're launching a website, you may spend nothing or your costs may go through the roof. In this article we discuss how much everything costs and what you get for what you pay (or don't pay).
+
+

What software do I need to build a website?

+
+
In this article we explain which software components you need when you're editing, uploading, or viewing a website.
+
+

What text editors are available?

+
+
In this article we highlight some things to think about when choosing and installing a text editor for web development.
+
+

How do I set up a basic working environment?

+
+
When working on a web project, you'll want to test it locally before you show it to the world. Some types of code require a server to test, and in this article we'll show you how to set one up. We'll also cover how to put a scalable structure in place so that your files stay organized even when your project gets big.
+
+

What are browser developer tools?

+
+
Every browser features a set of devtools for debugging HTML, CSS, and other web code. This article explains how to use the basic functions of your browser's devtools.
+
+

How do you make sure your website works properly?

+
+
So you've published your website online — very good! But are you sure it works properly? This article provides some basic troubleshooting steps.
+
+

How do you set up a local testing server?

+
+
+
+

This article explains how to set up a simple local testing server on your machine, and the basics of how to use it.

+
+
+
+

How do you upload files to a web server?

+
+
This article shows how to publish your site online with FTP tools — one fo the most common ways to get a website online so others can access it from their computers.
+
+

How do I use GitHub Pages?

+
+
This article provides a basic guide to publishing content using GitHub's gh-pages feature.
+
+

How do you host your website on Google App Engine?

+
+
Looking for a place to host your website? Here's a step-by-step guide to hosting your website on Google App Engine.
+
+

What tools are available to debug and improve website performance?

+
+
This set of articles shows you how to use the Developer Tools in Firefox to debug and improve performance of your website, using the tools to check the memory usage, the JavaScript call tree, the amount of DOM nodes being rendered, and more.
+
+ +

Desenho e acessibilidade

+ +

This section lists questions related to aesthetics, page structure, accessibility techniques, etc.

+ +
+
+

How do I start to design my website?

+
+
This article covers the all-important first step of every project: define what you want to accomplish with it.
+
+

What do common web layouts contain?

+
+
When designing pages for your website, it's good to have an idea of the most common layouts. This article runs thorugh some typical web layouts, looking at the parts that make up each one.
+
+

What is accessibility?

+
+
This article introduces the basic concepts behind web accessibility.
+
+

How can we design for all types of users?

+
+
This article provides basic techniques to help you design websites for any kind of user — quick accessibility wins, and other such things.
+
+

What HTML features promote accessibility?

+
+
This article describes specific features of HTML that can be used to make a web page more accessible to people with different disabilities.
+
+ +

Questões sobre HTML, CSS e JavaScript

+ +

Para soluções comuns para problemas de HTML/CSS/JavaScript, tente os seguintes artigos:

+ + diff --git a/files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html b/files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html new file mode 100644 index 0000000000..97655e6edf --- /dev/null +++ b/files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html @@ -0,0 +1,122 @@ +--- +title: >- + Qual é a diferença entre página da Web, site da Web, servidor da Web e + mecanismo de pesquisa? +slug: >- + Learn/Questoes_comuns/Qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa +tags: + - Mecânica da Web + - Principiante +translation_of: Learn/Common_questions/Pages_sites_servers_and_search_engines +--- +
+

In this article, we describe various web-related concepts: web pages, websites, web servers, and search engines. These terms are often confused by newcomers to the web or are incorrectly used. Let's learn what they each mean!

+
+ + + + + + + + + + + + +
Prerequisites:You should know how the Internet works.
Objective:Be able to describe the differences between a web page, a website, a web server, and a search engine.
+ +

Resumo

+ +

As with any area of knowledge, the web comes with a lot of jargon. Don't worry, we won't overwhelm you with all of it (we have a glossary if you're curious). However, there are a few basic terms you need to understand at the outset, since you'll hear these expressions all the time as you read on. It's easy to confuse these terms sometimes since they refer to related but different functionalities. In fact, you'll sometimes see these terms misused in news reports and elsewhere, so getting them mixed up is understandable!

+ +

We'll cover these terms and technologies in more detail as we explore further, but these quick definitions will be a great start for you:

+ +
+
web page
+
A document which can be displayed in a web browser such as Firefox, Google Chrome, Opera, Microsoft Internet Explorer or Edge, or Apple's Safari. These are also often called just "pages."
+
website
+
A collection of web pages which are grouped together and usually connected together in various ways. Often called a "web site" or simply a "site."
+
web server
+
A computer that hosts a website on the Internet.
+
search engine
+
A web service that helps you find other web pages, such as Google, Bing, Yahoo, or DuckDuckGo. Search engines are normally accessed through a web browser (e.g. you can perform search engine searches directly in the address bar of Firefox, Chrome, etc.) or through a web page (e.g. bing.com or duckduckgo.com).
+
+ +

Let's look at a simple analogy — a public library. This is what you would generally do when visiting a library:

+ +
    +
  1. Find a search index and look for the title of the book you want.
  2. +
  3. Make a note of the catalog number of the book.
  4. +
  5. Go to the particular section containing the book, find the right catalog number, and get the book.
  6. +
+ +

Let's compare the library with a web server:

+ + + +

Active learning

+ +

There is no active learning available yet. Please, consider contributing.

+ +

Deeper dive

+ +

So, let's dig deeper into how those four terms are related and why they are sometimes confused with each other.

+ +

Página da Web

+ +

A web page is a simple document displayable by a {{Glossary("browser")}}. Such documents are written in the {{Glossary("HTML")}} language (which we look into in more detail in other articles). A web page can embed a variety of different types of resources such as:

+ + + +
+

Note: Browsers can also display other documents such as {{Glossary("PDF")}} files or images, but the term web page specifically refers to HTML documents. Otherwise, we only use the term document.

+
+ +

All web pages available on the web are reachable through a unique address. To access a page, just type its address in your browser address bar:

+ +

Example of a web page address in the browser address bar

+ +

Sites da Web

+ +

A website is a collection of linked web pages (plus their associated resources) that share a unique domain name. Each web page of a given website provides explicit links—most of the time in the form of clickable portion of text—that allow the user to move from one page of the website to another.

+ +

To access a website, type its domain name in your browser address bar, and the browser will display the website's main web page, or homepage (casually referred as "the home"):

+ +

Example of a web site domain name in the browser address bar

+ +

The ideas of a web page and a website are especially easy to confuse for a website that contains only one web page. Such a website is sometimes called a single-page website.

+ +

Servidor da Web

+ +

A web server is a computer hosting one or more websites. "Hosting" means that all the web pages and their supporting files are available on that computer. The web server will send any web page from the website it is hosting to any user's browser, per user request.

+ +

Don't confuse websites and web servers. For example, if you hear someone say, "My website is not responding", it actually means that the web server is not responding and therefore the website is not available. More importantly, since a web server can host multiple websites, the term web server is never used to designate a website, as it could cause great confusion. In our previous example, if we said, "My web server is not responding", it means that multiple websites on that web server are not available.

+ +

Mecanismo de Pesquisa

+ +

Search engines are a common source of confusion on the web. A search engine is a special kind of website that helps users find web pages from other websites.

+ +

There are plenty out there: Google, Bing, Yandex, DuckDuckGo, and many more. Some are generic, some are specialized about certain topics. Use whichever you prefer.

+ +

Many beginners on the web confuse search engines and browsers. Let's make it clear: A browser is a piece of software that retrieves and displays web pages; a search engine is a website that helps people find web pages from other websites. The confusion arises because, the first time someone launches a browser, the browser displays a search engine's homepage. This makes sense, because, obviously, the first thing you want to do with a browser is to find a web page to display. Don't confuse the infrastructure (e.g., the browser) with the service (e.g., the search engine). The distinction will help you quite a bit, but even some professionals speak loosely, so don't feel anxious about it.

+ +

Here is an instance of Firefox showing a Google search box as its default startup page:

+ +

Example of Firefox nightly displaying a custom Google page as default

+ +

Passos Seguintes

+ + diff --git a/files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html b/files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html new file mode 100644 index 0000000000..389407247d --- /dev/null +++ b/files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html @@ -0,0 +1,182 @@ +--- +title: Como configurar um servidor local de testes? +slug: Learn/Questoes_comuns/Congiurar_um_servidor_de_testes_local +tags: + - Aprender + - Nodo + - PHP + - Principiante + - Python + - django + - servidores +translation_of: Learn/Common_questions/set_up_a_local_testing_server +--- +
+

Este artigo explica como configurar um servidor de testes local simples  na sua máquina, e como o utilizar.

+
+ + + + + + + + + + + + +
Pré-requisitos:pprimeiro, precisa de saber como é que a Internet funciona, e o que é um servidor da Web.
Objetivo:You will learn how to set up a local testing server.
+ +

Ficheiros locais vs. ficheiros remotos

+ +

Throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double clicking the HTML file, dragging and dropping it into the browser window, or choosing File > Open... and navigating to the HTML file. There are many ways to achieve this.

+ +

If the web address path starts with file:// followed by the path to the file on your local hard drive, a local file is being used. In contrast, if you view one of our examples hosted on GitHub (or an example on some other remote server), the web address will start with http:// or https://, to show that the file has been received via HTTP.

+ +

O problema com o teste de ficheiros locais

+ +

Some examples won't run if you open them as local files. This can be due to a variety of reasons, the most likely being:

+ + + +

Executar um servidor um servidor local de HTTP simples

+ +

To get around the problem of async requests, we need to test such examples by running them through a local web server. One of the easiest ways to do this for our purposes is to use Python's SimpleHTTPServer module.

+ +

To do this:

+ +
    +
  1. +

    Install Python. If you are using Linux or Mac OS X, it should be available on your system already. If you are a Windows user, you can get an installer from the Python homepage and follow the instructions to install it:

    + +
      +
    • Go to python.org
    • +
    • Under the Download section, click the link for Python "3.xxx".
    • +
    • At the bottom of the page, choose the Windows x86 executable installer and download it.
    • +
    • When it has downloaded, run it.
    • +
    • On the first installer page, make sure you check the "Add Python 3.xxx to PATH" checkbox.
    • +
    • Click Install, then click Close when the installation has finished.
    • +
    +
  2. +
  3. +

    Open your command prompt (Windows)/terminal (OS X/Linux). To check Python is installed, enter the following command:

    + +
    python -V
    +
  4. +
  5. +

    This should return a version number. If this is OK, navigate to the directory that your example is inside, using the cd command.

    + +
    # include the directory name to enter it, for example
    +cd Desktop
    +# use two dots to jump up one directory level if you need to
    +cd ..
    +
  6. +
  7. +

    Enter the command to start up the server in that directory:

    + +
    # If Python version returned above is 3.X
    +python -m http.server
    +# If Python version returned above is 2.X
    +python -m SimpleHTTPServer
    +
  8. +
  9. +

    By default, this will run the contents of the directory on a local web server, on port 8000. You can go to this server by going to the URL localhost:8000 in your web browser. Here you'll see the contents of the directory listed — click the HTML file you want to run.

    +
  10. +
+ +
+

Note: If you already have something running on port 8000, you can choose another port by running the server command followed by an alternative port number, e.g. python -m http.server 7800 (Python 3.x) or python -m SimpleHTTPServer 7800 (Python 2.x). You can then access your content at localhost:7800.

+
+ +

Running server-side languages locally

+ +

Python's SimpleHTTPServer module is useful, but it doesn't know how to run code written in languages such as PHP or Python. To handle that you'll need something more — exactly what you'll need depends on the server-side language you are trying to run. Here are a few examples:

+ + + +
+ + + + +
+
+
 
+ +
+
G
+ +
M
+ +
T
+
+ +
+
 
+ +
 
+
+ +
+ + + + + + + + + + + + +
+
 
+
+
 
+
+
 
+
+
 
+ +
 
+
+
 
+
+
 
+
+
+
+ +
 
+ +
 
+ +
 
+ +
A função de fala é limitada a 200 caracteres
+ +
+
 
+ + + + + + + + +
+
 
+
Opções : Histórico : Comentários : DonateEncerrar
+
+
+
diff --git a/files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html b/files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html new file mode 100644 index 0000000000..b490ab9789 --- /dev/null +++ b/files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html @@ -0,0 +1,234 @@ +--- +title: O que é um nome de domíno? +slug: Learn/Questoes_comuns/O_que_e_um_nome_de_dominio +tags: + - Infraestrutura + - Introdução + - Nomes de domínio + - Principiante + - Web +translation_of: Learn/Common_questions/What_is_a_domain_name +--- +
+

In this article we discuss domain names: what they are, how they are structured, and how to get one.

+
+ + + + + + + + + + + + +
Pré-requisitos:First you need to know how the Internet works and understand what URLs are.
Objetivo:Learn what domain names are, how they work, and why they are important.
+ +

Resumo

+ +

Domain names are a key part of the Internet infrastructure. They provide a human-readable address for any web server available on the Internet.

+ +

Any Internet-connected computer can be reached through a public {{Glossary("IP")}} Address, which consists of 32 bits for IPv4 (they are usually written as four numbers between 0 and 255, separated by dots (e.g., 173.194.121.32) or which consists of 128 bits for IPv6 (they are usually written as eight groups of 4 hexadecimal numbers, separated by colons (e.g., 2027:0da8:8b73:0000:0000:8a2e:0370:1337). Computers can handle those addresses easily, but people have a hard time finding out who's running the server or what service the website offers. IP addresses are hard to remember and might change over time. To solve all those problems we use human-readable addresses called domain names.

+ +

Aprendizagem Ativa

+ +

There is no active learning available yet. Please, consider contributing.

+ +

Deeper dive

+ +

Estrutura dos nomes de domínio

+ +

A domain name has a simple structure made of several parts (it might be one part only, two, three...), separated by dots and read from right to left:

+ +

Anatomy of the MDN domain name

+ +

Each of those  parts provides specific information about the whole domain name.

+ +
+
{{Glossary("TLD")}} (Top-Level Domain).
+
The TLD provides the most generic information. TLDs tell users the general purpose of the service behind the domain name. The most generic TLDs (.com, .org, .net) don't require web services to meet strict criteria, but some TLDs enforce stricter policies. For example, local TLDs such as .us, .fr, or .sh can require the service to be provided in a given language or hosted in a certain country.
+
Label (or component)
+
The labels are what follow the TLD. A label can be anything, from one letter to a full sentence. The label located right before the TLD can also be referred as a Secondary Level Domain (SLD). A domain name can have many labels (or components), it is not mandatory nor necessary to have 3 labels to form a domain name. For instance, www.inf.ed.ac.uk is a correct domain name. When controlling the "upper" part of a domain name (e.g. mozilla.org), one can create other domain names (sometimes called "subdomains") (e.g. developer.mozilla.org).
+
+ +

Comprar um nome de domínio

+ +

Who owns a domain name?

+ +

You cannot “buy a domain name”. You pay for the right to use a domain name for one or more years. You can renew your right, and your renewal has priority over other people's applications. But you never own the domain name.

+ +

Companies called registrars use domain name registries to keep track of technical and administrative information connecting you to your domain name.

+ +
+

Nota : For some domain name, it might not be a registrar which is in charge of keeping track. For instance, every domain name under .fire is managed by Amazon.

+
+ +

Encontrar um nome de domínio disponível

+ +

To find out whether a given domain name is available,

+ + + +
$ whois mozilla.org
+Domain Name:MOZILLA.ORG
+Domain ID: D1409563-LROR
+Creation Date: 1998-01-24T05:00:00Z
+Updated Date: 2013-12-08T01:16:57Z
+Registry Expiry Date: 2015-01-23T05:00:00Z
+Sponsoring Registrar:MarkMonitor Inc. (R37-LROR)
+Sponsoring Registrar IANA ID: 292
+WHOIS Server:
+Referral URL:
+Domain Status: clientDeleteProhibited
+Domain Status: clientTransferProhibited
+Domain Status: clientUpdateProhibited
+Registrant ID:mmr-33684
+Registrant Name:DNS Admin
+Registrant Organization:Mozilla Foundation
+Registrant Street: 650 Castro St Ste 300
+Registrant City:Mountain View
+Registrant State/Province:CA
+Registrant Postal Code:94041
+Registrant Country:US
+Registrant Phone:+1.6509030800
+
+ +

As you can see, I can't register mozilla.org because the Mozilla Foundation has already registered it.

+ +

On the other hand, let's see if I could register afunkydomainname.org:

+ +
$ whois afunkydomainname.org
+NOT FOUND
+
+ +

As you can see, the domain does not exist in the whois database (at the time of writing), so we could ask to register it. Good to know!

+ +

Obter um nome de domínio

+ +

The process is quite straightforward:

+ +
    +
  1. Go to a registrar's website.
  2. +
  3. Usually there is a prominent “Get a domain name” call to action. Click on it.
  4. +
  5. Fill out the form with all required details. Make sure especially that you have not misspelled your desired domain name. Once it's paid for, it's too late!
  6. +
  7. The registrar will let you know when the domain name is properly registered. Within a few hours, all DNS servers will have received your DNS information.
  8. +
+ +
+

Nota: In this process the registrar asks you for your real-world address. Make sure you fill it properly, since in some countries registrars may be forced to close the domain if they cannot provide a valid address.

+
+ +

Atualizar DNS

+ +

DNS databases are stored on every DNS server worldwide, and all these servers refer to a few ones called “authoritative name server” or “top-level DNS servers.” Whenever your registrar creates or updates any information for a given domain, the information must be refreshed in every DNS database. Each DNS server that knows about a given domain stores the information for some time before it is automatically invalidated and then refreshed (the DNS server queries an authoritative server again). Thus, it takes some time for DNS servers that know about this domain name to get the up-to-date information.

+ +
+

Nota : This time is often called propagation time. However this term is not precise since the update is not propagating itself (top → down). DNS servers queried by your computer (down) are the ones that fetch the information from the authoritative server (top) when they need it.

+
+ +

Como funciona um pedido de DNS?

+ +

As we already saw, when you want to display a webpage in your browser it's easier to type a domain name than an IP address. Let's take a look at the process:

+ +
    +
  1. Type mozilla.org in your browser's location bar.
  2. +
  3. Your browser asks your computer if it already recognizes the IP address identified by this domain name (using a local DNS cache). If it does, the name is translated to the IP address and the browser negotiates contents with the web server. End of story.
  4. +
  5. If your computer does not know which IP is behind the mozilla.org name, it goes on to ask a DNS server, whose job is precisely to tell your computer which IP address matches each registered domain name.
  6. +
  7. Now that the computer knows the requested IP address, your browser can negotiate contents with the web server.
  8. +
+ +

Explanation of the steps needed to obtain the result to a DNS request

+ +

Passos seguintes

+ +

Okay, we talked a lot about processes and architecture. Time to move on.

+ + + +
+ + + + + +
diff --git a/files/pt-pt/learn/common_questions/what_is_a_url/index.html b/files/pt-pt/learn/common_questions/what_is_a_url/index.html new file mode 100644 index 0000000000..b61a73433e --- /dev/null +++ b/files/pt-pt/learn/common_questions/what_is_a_url/index.html @@ -0,0 +1,231 @@ +--- +title: O que é um URL? +slug: Learn/Questoes_comuns/O_que_e_um_URL +tags: + - Infraestrutura + - Principiante + - URL +translation_of: Learn/Common_questions/What_is_a_URL +--- +
+

This article discusses Uniform Resource Locators (URLs), explaining what they are and how they're structured.

+
+ + + + + + + + + + + + +
Prerequisites:You need to first know how the Internet works, what a Web server is and the concepts behind links on the web.
Objective:You will learn what a URL is and how it works on the Web.
+ +

Resumo

+ +

With {{Glossary("Hypertext")}} and {{Glossary("HTTP")}}, URL is one of the key concepts of the Web. It is the mechanism used by {{Glossary("Browser","browsers")}} to retrieve any published resource on the web.

+ +

URL stands for Uniform Resource Locator. A URL is nothing more than the address of a given unique resource on the Web. In theory, each valid URL points to a unique resource. Such resources can be an HTML page, a CSS document, an image, etc. In practice, there are some exceptions, the most common being a URL pointing to a resource that no longer exists or that has moved. As the resource represented by the URL and the URL itself are handled by the Web server, it is up to the owner of the web server to carefully manage that resource and its associated URL.

+ +

Aprendizagem Ativa

+ +

There is no active learning available yet. Please, consider contributing.

+ +

Deeper dive

+ +

Basics: anatomy of a URL

+ +

Here are some examples of URLs:

+ +
https://developer.mozilla.org
+https://developer.mozilla.org/en-US/docs/Learn/
+https://developer.mozilla.org/en-US/search?q=URL
+ +

Any of those URLs can be typed into your browser's address bar to tell it to load the associated page (resource).

+ +

A URL is composed of different parts, some mandatory and others optional. Let's see the most important parts using the following URL:

+ +
http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument
+ +
+
Protocol
+
http:// is the protocol. It indicates which protocol the browser must use. Usually it is the HTTP protocol or its secured version, HTTPS. The Web requires one of these two, but browsers also know how to handle other protocols such as mailto: (to open a mail client) or ftp: to handle file transfer, so don't be surprised if you see such protocols.
+
Domaine Name
+
www.example.com is the domain name. It indicates which Web server is being requested. Alternatively, it is possible to directly use an {{Glossary("IP address")}}, but because it is less convenient, it is not often used on the Web.
+
Port
+
:80 is the port. It indicates the technical "gate" used to access the resources on the web server. It is usually omitted if the web server uses the standard ports of the HTTP protocol (80 for HTTP and 443 for HTTPS) to grant access to its resources. Otherwise it is mandatory.
+
Path to the file
+
/path/to/myfile.html is the path to the resource on the Web server. In the early days of the Web, a path like this represented a physical file location on the Web server. Nowadays, it is mostly an abstraction handled by Web servers without any physical reality.
+
Parameters
+
?key1=value1&key2=value2 are extra parameters provided to the Web server. Those parameters are a list of key/value pairs separated with the & symbol. The Web server can use those parameters to do extra stuff before returning the resource. Each Web server has its own rules regarding parameters, and the only reliable way to know if a specific Web server is handling parameters is by asking the Web server owner.
+
Anchor
+
#SomewhereInTheDocument is an anchor to another part of the resource itself. An anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content located at that "bookmarked" spot. On an HTML document, for example, the browser will scroll to the point where the anchor is defined; on a video or audio document, the browser will try to go to the time the anchor represents. It is worth noting that the part after the #, also known as the fragment identifier, is never sent to the server with the request.
+
+ +

{{Note('There are some extra parts and some extra rules regarding URLs, but they are not relevant for regular users or Web developers. Don\'t worry about this, you don\'t need to know them to build and use fully functional URLs.')}}

+ +

You might think of a URL like a regular postal mail address: the protocol represents the postal service you want to use, the domain name is the city or town,  and the port is like the zip code; the path represents the building where your mail should be delivered; the parameters represent extra information such as the number of the apartment in the building; and, finally, the anchor represents the actual person to whom you've addressed your mail.

+ +

Como utilizar os URLs

+ +

Any URL can be typed right inside the browser's address bar to get to the resource behind it. But this is only the tip of the iceberg!

+ +

The {{Glossary("HTML")}} language — which will be discussed later on — makes extensive use of URLs:

+ + + +

Other technologies, such as {{Glossary("CSS")}} or {{Glossary("JavaScript")}}, use URLs extensively, and these are really the heart of the Web.

+ +

URLs absolutos vs URLs relativos

+ +

What we saw above is called an absolute URL, but there is also something called a relative URL. Let's examine what that distinction means in more detail.

+ +

The required parts of a URL depend to a great extent on the context in which the URL is used. In your browser's address bar, a URL doesn't have any context, so you must provide a full (or absolute) URL, like the ones we saw above. You don't need to include the protocol (the browser uses HTTP by default) or the port (which is only required when the targeted Web server is using some unusual port), but all the other parts of the URL are necessary.

+ +

When a URL is used within a document, such as in an HTML page,  things are a bit different. Because the browser already has the document's own URL, it can use this information to fill in the missing parts of any URL available inside that document. We can differentiate between an absolute URL and a relative URL by looking only at the path part of the URL. If the path part of the URL starts with the "/" character, the browser will fetch that resource from the top root of the server, without reference to the context given by the current document.

+ +

Let's look at some examples to make this clearer.

+ +

Exemplos de URLs absolutos

+ +
+
Full URL (the same as the one we used before)
+
+
https://developer.mozilla.org/en-US/docs/Learn
+
+
Implicit protocol
+
+
//developer.mozilla.org/en-US/docs/Learn
+ +

In this case, the browser will call that URL with the same protocol as the the one used to load the document hosting that URL.

+
+
Implicit domain name
+
+
/en-US/docs/Learn
+ +

This is the most common use case for an absolute URL within an HTML document. The browser will use the same protocol and the same domain name as the one used to load the document hosting that URL. Note: it isn't possible to omit the domain name without omitting the protocol as well.

+
+
+ +

Exemplos de URLs relativos

+ +

To better understand the following examples, let's assume that the URLs are called from within the document located at the following URL: https://developer.mozilla.org/en-US/docs/Learn

+ +
+
Sub-resources
+
+
Skills/Infrastructure/Understanding_URLs
+
+ Because that URL does not start with /, the browser will attempt to find the document in a sub-directory of the one containing the current resource. So in this example,  we really want to reach this URL: https://developer.mozilla.org/en-US/docs/Learn/Skills/Infrastructure/Understanding_URLs
+
Going back in the directory tree
+
+
../CSS/display
+ +

In this case, we use the ../ writing convention — inherited from the UNIX file system world — to tell the browser we want to go up from one directory. Here we want to reach this URL: https://developer.mozilla.org/en-US/docs/Learn/../CSS/display, which can be simplified to: https://developer.mozilla.org/en-US/docs/CSS/display

+
+
+ +

URLs semânticos

+ +

Despite their very technical flavor, URLs represent a human-readable entry point for a Web site. They can be memorized, and anyone can enter them into a browser's address bar. People are at the core of the Web, and so it is considered best practice to build what is called semantic URLs.  Semantic URLs  use words with inherent meaning that can be understood by anyone, regardless of their technical know-how.

+ +

Linguistic semantics are of course irrelevant to computers. You've probably often seen URLs that look like mashups of random characters. But there are many advantages  to creating human-readable URLs:

+ + + +

Passos seguintes

+ + + +
+ + + + + +
diff --git a/files/pt-pt/learn/common_questions/what_is_a_web_server/index.html b/files/pt-pt/learn/common_questions/what_is_a_web_server/index.html new file mode 100644 index 0000000000..a91ef08d6c --- /dev/null +++ b/files/pt-pt/learn/common_questions/what_is_a_web_server/index.html @@ -0,0 +1,198 @@ +--- +title: O que é um servidor da Web? +slug: Learn/Questoes_comuns/O_que_e_um_servidor_da_Web +tags: + - Infraestrutura + - Principiante +translation_of: Learn/Common_questions/What_is_a_web_server +--- +
+

Neste artigo, nós examinamos quais são os servidores da Web, como é que estes funcionam, e por que é que eles são importantes.

+
+ + + + + + + + + + + + +
Pré-requisitos:You should already know how the Internet works, and understand the difference between a web page, a web site, a web server and a search engine.
Objetivo:You will learn what a web server is and gain a general understanding of how it works.
+ +

Resumo

+ +

"Web server" can refer to hardware or software, or both of them working together.

+ +
    +
  1. On the hardware side, a web server is a computer that stores a website's component files (e.g. HTML documents, images, CSS stylesheets, and JavaScript files) and delivers them to the end-user's device. It is connected to the Internet and can be accessed through a domain name like mozilla.org.
  2. +
  3. On the software side, a web server includes several parts that control how web users access hosted files, at minimum an HTTP server. An HTTP server is a piece of software that understands {{Glossary("URL","URLs")}} (web addresses) and {{Glossary("HTTP")}} (the protocol your browser uses to view webpages).
  4. +
+ +

At the most basic level, whenever a browser needs a file hosted on a web server, the browser requests the file via HTTP. When the request reaches the correct web server (hardware), the HTTP server (software) sends the requested document back, also through HTTP.

+ +

Basic representation of a client/server connection through HTTP

+ +

To publish a website, you need either a static or a dynamic web server.

+ +

A static web server, or stack, consists of a computer (hardware) with an HTTP server (software). We call it "static" because the server sends its hosted files "as-is" to your browser.

+ +

A dynamic web server consists of a static web server plus extra software, most commonly an application server and a database. We call it "dynamic" because the application server updates the hosted files before sending them to your browser via the HTTP server.

+ +

For example, to produce the final webpages you see in the browser, the application server might fill an HTML template with contents from a database. Sites like MDN or Wikipedia have many thousands of webpages, but they aren't real HTML documents, only a few HTML templates and a giant database. This setup makes it easier and quicker to maintain and deliver the content.

+ +

Aprendizagem ativa

+ +

Ainda não está disponível nenhuma aprendizagem ativa. Por favor, considere contribuir.

+ +

Deeper dive

+ +

To fetch a webpage, as we already said, your browser sends a request to the web server, which proceeds to search for the requested file in its own storage space. On finding the file, the server reads it, processes it as needed, and sends it to the browser. Let's look at those steps in more detail.

+ +

Hosting files

+ +

A web server first has to store the website's files, namely all HTML documents and their related assets, including images, CSS stylesheets, JavaScript files, fonts, and videos.

+ +

Technically, you could host all those files on your own computer, but it's far more convenient to store them all on a dedicated web server that

+ + + +

For all these reasons, finding a good hosting provider is a key part of building your website. Dig through the various services companies offer and choose one that fits your needs and your budget (services range from free to thousands of dollars per month). You can find more details in this article.

+ +

Once you set up a web hosting solution, you just have to upload your files to your web server.

+ +

Communicating through HTTP

+ +

Second, a web server provides support for {{Glossary("HTTP")}} (Hypertext Transfer Protocol). As its name implies, HTTP specifies how to transfer hypertext (i.e., linked web documents) between two computers.

+ +

A protocol is a set of rules for communication between two computers. HTTP is a textual, stateless protocol.

+ +
+
Textual
+
All commands are plain-text and human-readable.
+
Stateless
+
Neither the server nor the client remember previous communications. For example, relying on HTTP alone, a server cannot remember a password you typed or what step you're on in a transaction. You need an application server for tasks like that. (We'll cover that sort of technology in further articles.)
+
+ +

HTTP provides clear rules for how a client and server communicate. We'll cover HTTP itself in a technical article later on. For now, just be aware of these things:

+ + + +

The MDN 404 page as an example of such error pageOn a web server, the HTTP server is responsible for processing and answering incoming requests.

+ +
    +
  1. On receiving a request, an HTTP server first checks whether the requested URL matches an existing file.
  2. +
  3. If so, the web server sends the file content back to the browser. If not, an application server builds the necessary file.
  4. +
  5. If neither process is possible, the web server returns an error message to the browser, most commonly "404 Not Found". (That error is so common that many web designers spend quite some time designing 404 error pages.)
  6. +
+ +

Static vs. dynamic content

+ +

Roughly speaking, a server can serve either static or dynamic content. "Static" means "served as-is". Static websites are the easiest to set up, so we suggest you make your first site a static site.

+ +

"Dynamic" means that the server processes the content or even generates it on the fly from a database. This solution provides more flexibility, but the technical stack becomes more difficult to handle, making it dramatically more complex to build the website.

+ +

Take for example the page you're reading right now. On the web server hosting it, there is an application server that takes article content from a database, formats it, puts it inside some HTML templates, and sends you the results. In this case, the application server is called Kuma and is built with Python (using the Django framework). The Mozilla team built Kuma for the specific needs of MDN, but there are many similar applications built on many other technologies.

+ +

There are so many application servers that it's pretty hard to suggest a particular one. Some application servers cater to specific website categories like blogs, wikis or e-shops; others, called {{Glossary("CMS", "CMSs")}} (content management systems), are more generic. If you're building a dynamic website, take the time to choose a tool that fits your needs. Unless you want to learn some web server programming (which is an exciting area in itself!), you don't need to create your own application server. That's just reinventing the wheel.

+ +

Passos seguintes

+ +

Now that you are familiar with web servers, you could:

+ + + +
+ + + + + +
diff --git a/files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html b/files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html new file mode 100644 index 0000000000..b73abb297f --- /dev/null +++ b/files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html @@ -0,0 +1,135 @@ +--- +title: Cascata e herança +slug: Web/CSS/Como_começar/Cascata_e_herança +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks/Cascade_and_inheritance +translation_of_original: Web/Guide/CSS/Getting_started/Cascading_and_inheritance +--- +

{{ PreviousNext("CSS:Como começar:Como o CSS trabalha", "CSS:Como começar:Seletores") }}

+ +

Esta página esboça como folhas de estilo interagem numa cascata, e como os elementos subordinados herdam o estilo do elementos primários.

+ +

Você alterará à sua folha de estilo de amostra, usando herança para mudar o estilo de muitas partes do seu documento em um passo.

+ +

Informação: Cascata e herança

+ +

O estilo final para um elemento pode ser especificado em muitos lugares diferentes, que pode interagir num meio complexo. Esta interação complexa faz CSS poderoso, mas às vezes isto pode deixar confuso e difícil de depurar.

+ +

Três códigos principais de informação de estilo formam uma cascata. Eles são:

+ + + +

O estilo do usuário modifica o estilo padrão do navegador. O estilo do autor do documento então modifica algum outro estilo. Neste tutorial, você é o autor do seu documeto de amostra, e você trabalha somente com folhas de estilo do autor.

+ + + + + + + + +
Exemplo
Quando você lê este documento no seu navegador Mozilla, parte do estilo que você vê, vem do padrão do seu navegador para HTML. +

Parte do estilo deve vir das configurações do seu navegador em Opções, ou de um arquivo userConten.css no seu perfil no navegador.

+ +

Parte do seu estilo vem de folhas de estilo ligadas ao documento pelo server do wiki.

+
+ +


+ Quando você abre seu documento de amostra no seu navegador, os elementos STRONG são mais fortes do que o resto do texto. Isto vem do estilo padrão do seu navegador para o HTML.

+ +

Os elementos STRONG são vermelhos, Isto vem da sua folha de estilo de amostra.

+ +

Os elementos STRONG as vezes também herdam muito do estilo de elemento P, pois eles são subordinados. No mesmo caminho, o elemento P herda muito do estilo do elemento BODY.

+ +

Para estilos em cascata, o autor das folhas de estilo tem prioridade, depois o leitor das folhas de estilo, e por último o padrão do navegador.

+ +

Para estilos em herança, um nó subordinado tem prioridade sobre o estilo que herdou do nó principal.

+ +

Estas não são as únicas propriedades que se aplicam. Uma página posterior neste turorial explicará mais.

+ + + + + + + + +
Mais detalhes
CSS às vezes providencia um meio para o leitor anular o estilo do autor do documento, usando a palavra-chave !important. +

Este meio é para o autor do documento, você não pode sempre predizer exatamente o que os leitores verão.

+ +

Se você quer saber todos os detalhes sobre cascata e herança, veja Assigning property values, Cascading, and Inheritance na CSS Specification.

+
+ +

Ação: Usando herança

+ +

Edite seu arquivo de amostra CSS.

+ +

Adicione esta linha copiando e colando isto. Não importa realmente se você adicionar a linha antes ou depois da que já está lá. Entretando, adicionar isto no topo é mais lógico pois no seu documento o elemento P é primário ao elemento STRONG:

+ +
p {color: blue; text-decoration: underline;}
+
+ +

Agora atualize seu navegador para ver o efeito no seu documento de amostra. O sublinhado afeta todo o texto no parágrafo, incluindo as letras iniciais. Os elementos STRONG herdaram o estilo sublinhado do elemento primário P.

+ +

Mas os elementos STRONG ainda são vermelhos. A cor vermelha é própria do estilo, então isto tem prioridade sobre a cor azul do seu elemento primário P.

+ + + + + + + + +
+ + + + + + + +
Antes
Cascading Style Sheets
+
+ + + + + + + +
Depois
Cascading Style Sheets
+
+ +

 

+ + + + + + + + +
Desafio
Mude sua folha de estilo deixando somente as letras vermelhas sublinhadas: + + + + + + +
Cascading Style Sheets
+
+ +

 

+ +

O que vem depois?

+ +

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

+ +

Sua folha de estilo de amostra especifica o estilo para os tags, P e STRONG, mudando o estilo dos elementos correspondentes em todo o seu documento original. A próxima página descreve como espeficar estilos em meios mais seletivos: Seletores

+ +

{{ PreviousNext("CSS:Como começar:Como o CSS trabalha", "CSS:Como começar:Seletores") }}

diff --git a/files/pt-pt/learn/css/building_blocks/index.html b/files/pt-pt/learn/css/building_blocks/index.html new file mode 100644 index 0000000000..dff3dfb0ac --- /dev/null +++ b/files/pt-pt/learn/css/building_blocks/index.html @@ -0,0 +1,359 @@ +--- +title: Caixas +slug: Web/CSS/Como_começar/Caixas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks +translation_of_original: Web/Guide/CSS/Getting_started/Boxes +--- +

{{ PreviousNext("CSS:Como começar:Listas", "CSS:Como começar:Disposição") }}

+ +

Esta página descreve como você pode usar as CSS para controlar o espaço que um elemento ocupa quando é exibido.

+ +

Em seu documento de amostra, você muda o espaçamento e adiciona regras decorativas.

+ +

Informação: Caixas

+ +

Quando seu navegador exibe um elemento, o elemento ocupa um espaço. Existem quatro partes do espaço que ele ocupa.

+ +

No meio, está o espaço que o elemento precisa para exibir seu conteúdo. Em torno disso, está o enchimento. Em torno disso, está a borda. Em torno disso, está a margem.

+ + + + + + + + +
+
+

margin

+ +

border

+ +
+

padding

+ +
+

element

+
+
+
+ +

A paleta cinza mostra partes da disposição.

+
+
+

 

+ +

 

+ +
+

 

+ +
+

element

+
+
+
+ +

Isto é o que você vê em seu navegador.

+
+ +

O enchimento, a borda e a margem podem ter diferentes tamanhos no topo, na direita, em baixo e na esquerda do elemento. Qualquer ou todos estes tamanhos podem ser zero.

+ +

O enchimento é sempre da mesma cor do fundo do elemento. Então quando você configura a cor de fundo, você vê a cor aplicada ao próprio elemento e ao seu enchimento. A margem é sempre transparente.

+ + + + + + + + +
+
+

margin

+ +

border

+ +
+

padding

+ +
+

element

+
+
+
+ +

O elemento tem um fundo verde.

+
+
+

 

+ +

 

+ +
+

 

+ +
+

element

+
+
+
+ +

É isto que você vê no seu navegador.

+
+ +

Bordas

+ +

Você pode usar bordas para decorar elementos com linhas ou caixas.

+ +

Para especificar a mesma borda em torno de todo o elemento, use a propriedade border. Especifique a largura (usualmente em pixels para exibir na tela), o estilo, e a cor.

+ +

Os estilos são:

+ + + + + + + + + + + + + + + + +
+
solid
+
+
dotted
+
+
dashed
+
+
double
+
+
inset
+
+
outset
+
+
ridge
+
+
groove
+
+ +

Você pode também configurar o estilo para none ou hidden para remover a borda explicitamente, ou configurar a cor para transparent para fazer a borda invisível sem mudar a disposição.

+ +

Para especificar bordas em um lado de cada vez, use as propriedades: border-top, border-right, border-bottom, border-left. Você pode usar isto para especificar uma borda em somente um lado, ou diferentes bordas em diferentes lados.

+ + + + + + + + +
Exemplos
Esta regra configura a cor de fundo e a borda do topo dos elementos do cabeçalho: +
+
+h3 {
+  border-top: 4px solid #7c7; /* mid green */
+  background-color: #efe;     /* pale green */
+  color: #050;                /* dark green */
+  }
+
+
+ +

O resultado deve ser como este:

+ + + + + + + +
+

Cabeçalho elegante

+
+ +


+ Esta regra faz as imagens fáceis de ver dando-as uma borda com um cinza-médio em toda a volta:

+ +
+
+img {border: 2px solid #ccc;}
+
+
+ +

O resultado deve ser como este:

+ + + + + + + + +
Imagem:Image:Blue-rule.png
+
+ +

Margens e enchimento

+ +

Use margens e enchimento para ajustar a posição dos elementos e para criar espaços ao redor deles.

+ +

Use a propriedade margin ou a propriedade padding para configurar a largura da margem ou do enchimento respectivamente.

+ +

Se você especificar uma largura, isto se aplicará em torno de todo o elemento (topo, direita, baixo e esquerda).

+ +

Se você especificar duas larguras, a primeira se aplicará ao topo e à baixo, e a segunda à direita e à esquerda.

+ +

Você pode especificar todas as quatro larguras na ordem: topo, direita, baixo, esquerda.

+ + + + + + + + +
Exemplo
Esta regra diferencia parágrafos com a classe remark dando-os uma borda vermelha em toda a sua volta. +

O Enchimento em toda a volta separa um pouco a borda do texto.

+ +

Uma margem esquerda identifica o parágrafo relativo ao resto do texto:

+ +
+
+p.remark {
+  border: 2px solid red;
+  padding: 4px;
+  margin-left: 24px;
+  }
+
+
+ +

O resultado deve ser como este:

+ + + + + + + +
+

Aqui está um parágrafo normal.

+ +

Aqui está um com observação.

+
+
+ + + + + + + + +
Mais detalhes
Quando você usa margens e enchimento para ajustar o modo como os elementos são exibidos, suas regras de estilo interagem com o padrão dos navegadores de maneiras que podem ser complexas. +

Navegadores diferentes exibem os elementos diferentemente. Os resultados podem ser similares antes de sua folha de estilo mudar coisas. Algumas vezes isto pode fazer sua folha de estilo dar resultados surpreendedores.

+ +

Para ter o resultado que você precisa, você pode ter que mudar a marcação do seu documento. A próxima página deste tutorial tem mais informações sobre isto.

+ +

Para informações detalhas sobre enchimento, margens e bordas, veja Box model em CSS Specification.

+
+ +

Ação: Adicionando bordas

+ +

Edite seu arquivo CSS. Adicione esta regra para desenhar uma linha até o fim da página sobre cada cabeçalho:

+ +
+
h3 {border-top: 1px solid gray;}
+
+
+ +

Se você pegou o desafio na página anterior, modifique a regra que você criou, se não, adicione esta nova regra para adicionar um espaço em baixo de cada item da lista:

+ +
+
li {
+  list-style: lower-roman;
+  margin-bottom: 8px;
+  }
+
+
+ +

Atualize seu navegador para ver o resultado:

+ + + + + + + +
+

(A) Os oceanos

+ +
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+ +

(B) Parágrafos numerados

+ +

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+ + + + + + + + +
Desafio
Adicione uma regra à sua folha de estilo, fazendo um borda larga em toda a volta dos oceanos em uma cor que te lembre o mar — algo como isto: + + + + + + +
+

(A) Os oceanos

+ +
+
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+
+ +

(B) Parágrafos numerados

+ +

. . .

+
+ +

(Não é necessário fazer exatamente com a largura e a cor que usadas aqui.)

+
+ +

O que vem depois

+ +

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

+ +

Especificando margens e enchimento, você modificou a disposição do seu documento. Na próxima página você poderá mudar a disposição do seu documento de outras maneiras: Disposição

+ +

{{ PreviousNext("CSS:Como começar:Listas", "CSS:Como começar:Disposição") }}

diff --git a/files/pt-pt/learn/css/building_blocks/selectors/index.html b/files/pt-pt/learn/css/building_blocks/selectors/index.html new file mode 100644 index 0000000000..f9d4505614 --- /dev/null +++ b/files/pt-pt/learn/css/building_blocks/selectors/index.html @@ -0,0 +1,208 @@ +--- +title: Seletores +slug: Web/CSS/Como_começar/Seletores +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks/Selectors +translation_of_original: Web/Guide/CSS/Getting_started/Selectors +--- +

{{ PreviousNext("CSS:Como começar:Cascata e herança", "CSS:Como começar:CSS legível") }}

+ +

Esta página explica como você pode aplicar estilos seletivamente, e como diferentes tipos de seletor têm propriedades diferentes.

+ +

Você adiciona alguns atributos às tags do seu documento de amostra, e usa estes atributos em sua folha de estilo de amostra.

+ +

Informação: Seletores

+ +

CSS tem sua própria terminologia para descrever a linguagem CSS. Anteriormente neste tutorial, você criou uma linha em sua folha de estilo com esta:

+ +
+
strong {color: red;}
+
+
+ +

Na terminologia das CSS, esta linha inteira é uma regra. Esta regra começa com STRONG, que é um seletor. Isto seleciona que elementos no DOM a regra se aplicará.

+ + + + + + + + +
Mais detalhes
A parte interior das chaves é a declaração. +

A palavra-chave color é uma propriedade, e red é um valor.

+ +

O ponto-e-vírgula depois do par propriedade-valor separa isto de outros pares propriedade-valor na mesma descrição.

+ +

Este tutorial refere-se a um seletor STRONG, como um seletor de tag. A Especificação das CSS refere-se a isto como um seletor de tipo.

+
+ +

Esta página do tutorial explica mais sobre os seletores que você pode usar nas regras das CSS.

+ +

Em adição aos nomes de tags, você pode usar valores de atributo nos seletores. Isto permite a você que as regras tornem-se mais específicas.

+ +

Dois atributos tem estado especial para as CSS. Eles são class e id.

+ +

Use o atributo class em uma tag para nomear a tag com um nome de classe. Isto é, o nome que você escolher para a classe.

+ +

Na sua folha de estilo, digite um registro completo (período) antes do nome de classe quando você usá-lo em um seletor.

+ +

Use o atributo id em uma tag para nomear a tag com um nome de id. Isto é, o nome que você escolher para o id. O nome do id deve ser único no documento.

+ +

Na sua folha de estilo, digite um sinal de número (#) antes do id quando você usá-lo em um seletor.

+ + + + + + + + +
Exemplos
Este tag HTML tem ambos os atributos class e id. +
+
+<P class="key" id="principal">
+
+
+ +

O id, principal, deve ser o único no documento, mas outras tags no documento podem ter o mesmo nome de classe, key.

+ +

Em uma folha de estilo CSS, esta regra faz todos os elementos da classe key verdes. (Eles podem não ser todos elementos P.)

+ +
+
+.key {color: green;}
+
+
+ +

Esta regra faz um elemento com o id principal negrito:

+ +
+
+#principal {font-weight: bolder;}
+
+
+
+ +

Se mais de uma regra se aplicar a um elemento e especificar a mesma propriedade, então CSS dará prioridade para a regra que tiver o seletor mais específico. Um seletor id é mais específíco que um seletor classe, que por sua vez é mais específico que um seletor tag.

+ + + + + + + + +
Mais detalhes
Você pode combinar seletores para fazer um seletor mais específico. +

Por exemplo, o seletor .key seleciona todos os elementos que tem o nome de classe key. O seletor p.key seleciona somente os elementos P que tiverem o nome de classe key.

+ +

Você não está restrito aos dois atributos especiais, class e id. Você pode especificar outros atributos igualando entre colchetes. Por exemplo, o seletor {{ mediawiki.external('type=button') }} seleciona todos os elementos que tiverem um atributo type com o valor button.

+ +

Uma página posterior deste tutorial (Tabelas) tem informações sobre seletores complexos baseados em parentescos.

+ +

Para um informação completa sobre seletores, veja Selectors na CSS Specification.

+
+ +

Se sua folha de estilo tiver regras conflitantes e elas estiverem igualmente especificadas, então CSS dará prioridade para a regra que foi especificada por último na folha de estilo.

+ +

Quando você tiver um problema com regras conflitantes, tente resolvê-lo fazendo uma das regras mais especificada, então ela terá prioridade. Se você não puder fazer isto, tente mover uma das regras para mais perto do fim da folha de estilo, então esta terá prioridade.

+ +

Ação: Usando seletores de classe e id

+ +

Edite seu arquivo HTML, e duplique o paragrafo copiando e colando-o. Então adicione os atributos de id e classe na primeira cópia, e um id na segunda cópia como mostrado abaixo. Um alternativa é copiar e colar o arquivo inteiro novamente:

+ +
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<HTML>
+  <HEAD>
+  <TITLE>Documento de amostra</TITLE>
+  <LINK rel="stylesheet" type="text/css" href="style1.css">
+  </HEAD>
+  <BODY>
+    <P id="first">
+      <STRONG class="carrot">C</STRONG>ascading
+      <STRONG class="spinach">S</STRONG>tyle
+      <STRONG class="spinach">S</STRONG>heets
+    </P>
+    <P id="second">
+      <STRONG>C</STRONG>ascading
+      <STRONG>S</STRONG>tyle
+      <STRONG>S</STRONG>heets
+    </P>
+  </BODY>
+</HTML>
+
+
+ +

Agora edite seu arquivo CSS. Substitua os componentes inteiros com:

+ +
+
strong {color: red;}
+.carrot {color: orange;}
+.spinach {color: green;}
+#first {font-style: italic;}
+
+
+ +


+ Atualize seu navegador para ver o resultado:

+ + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ +


+ Você pode tentar re-dispor as linhas no seu arquivo CSS para mostrar que a ordem não muda o efeito.

+ +

Os seletores de classe .carrot e .spinach tem prioridade sobre o seletor de tag STRONG.

+ +

O seletor id #first tem prioridade sobre a classe o os seletores de tag.

+ + + + + + + + +
Desafios
Sem mudar seu arquivo HTML, adicione uma única regra para seu arquivo CSS deixando todas as letras iniciais da mesma cor que estão agora, mas fazendo todo o segundo parágrafo aparecer em azul: + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ +

Agora mude a regra que você acabou de adicionar (sem mudar mais nenhuma coisa), para fazer o primeiro parágrafo em azul também:

+ + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+
+ +

O que vem depois?

+ +

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

+ +

Sua folha de estilo de amostra está começando a parecer densa e complicada. A próxima página descreve caminhos para fazer o CSS mais fácil de ler: CSS legível

+ +

{{ PreviousNext("CSS:Como começar:Cascata e herança", "CSS:Como começar:CSS legível") }}

diff --git a/files/pt-pt/learn/css/building_blocks/styling_tables/index.html b/files/pt-pt/learn/css/building_blocks/styling_tables/index.html new file mode 100644 index 0000000000..ff21a00c82 --- /dev/null +++ b/files/pt-pt/learn/css/building_blocks/styling_tables/index.html @@ -0,0 +1,655 @@ +--- +title: Tabelas +slug: Web/CSS/Como_começar/Tabelas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks/Styling_tables +translation_of_original: Web/Guide/CSS/Getting_started/Tables +--- +

{{ PreviousNext("CSS:Como começar:Disposição", "CSS:Como começar:Mídia") }}

+ +

Esta página descreve seletores mais avançados, e algumas maneiras específicas para estilizar tabelas.

+ +

Você cria um novo documento de amostra contendo uma tabela, e uma folha de estilo para isto.

+ +

Informação: Mais seletores

+ +

CSS possui algumas maneiras para selecionar elementos baseadas nas relações entre eles. Você pode usá-las para fazer seletores que sejam mais específicos.

+ +

Aqui está um sumário de seletores baseados em relações:

+ + + + + + + + + + + + + + + + + + + + + + + + +
SeletorSeleciona
A EQualquer elemento E que seja descendente de um elemento A (isso é: um subitem, ou um subitem de um sub item, etc.)
A > EQualquer elemento E que seja subitem de um elemento A
E:first-childQualque elemento E que seja o primeiro subitem do seu principal
B + EQualquer elemento E que seja o próximo irmão de um elemento B (isso é: o próximo subitem do mesmo principal)
+ +

Você pode combinar isto para expressar relações complexas.

+ +

Você pode também usar o símbolo * (asterisco) para dizer "qualquer elemento".

+ + + + + + + + +
Exemplo
Uma tabela HTML tem um atributo id, mas suas linhas e células não tem identificadores individuais: +
+
+<TABLE id="data-table-1">
+...
+<TR>
+<TD>Prefix</TD>
+<TD>0001</TD>
+<TD>default</TD>
+</TR>
+...
+
+
+ +

Estas regras fazem a primeira célula em cada linha em negrito, e a segunda célula em cada linha monoespaçada. Elas afetam somente uma tabela específica no documento:

+ +
+
    +
  1. data-table-1 td:first-child {font-weight: bolder;}
  2. +
  3. data-table-1 td:first-child + td {font-family: monospace;}
  4. +
+
+ +

O resultado é algo como isto:

+ + + + + + + +
+ + + + + + + + +
Prefix0001default
+
+
+ + + + + + + + +
Mais detalhes
De maneira usual, se você faz um seletor mais específico então você aumenta sua prioridade. +

Usando estas técnicas, você evita precisar especificar atributos class ou id em muitas tags no seu documento. Em vez disso, CSS faz o trabalho.

+ +

Em grandes projetos onde a velocidade é importante, você pode fazer suas folhas de estilo mais eficientes evitando regras complexas que dependem da relação entre elementos.

+ +

Para detalhes completos sobre seletores, veja Selectors em CSS Specification.

+
+ +

Informação: Tabelas

+ +

Uma tabela é um arranjo de informação em uma grade retangular. Algumas tabelas podem ser complexas, e para tabelas complexas diferentes navegadores podem exibir diferentes resultados.

+ +

Quando você desenha seu documento, use e a tabela para expressar as relações entre as peças da informação. Então não importará se os diferentes navegadores apresentarem a informação de maneiras levemente diferentes, pois o significado ainda pode ser compreendido.

+ +

Não use tabelas de maneiras não usuais para produzir disposições visuais particulares. As técnicas na página anterior deste tutorial (Disposição) são melhores para isto.

+ +

Estrutura da tabela

+ +

Em uma tabela, cada peça de informação é exibida em uma célula.

+ +

As células em uma linha horizontal na página compõem uma linha.

+ +

Em algumas tabelas, as linhas podem ser agrupadas. Um grupo especial de linhas no começo da tabela é o cabeçalho. Um grupo especial de linhas no final da tabela é o rodapé. As linhas principais na tabela são o corpo, e elas podem também estar em grupos.

+ +

As células em uma linha vertical na página compõem uma coluna, mas as colunas têm usos limitados nas tabelas das CSS.

+ + + + + + + + +
Exemplo
A tabela de seletores próxima ao topo desta página tem dez células em cinco linhas. +

A primeira linha é o cabeçalho. As outras quatro linhas são o corpo. Não há um rodapé.

+ +

Ela tem duas colunas.

+
+ +

Este tutorial somente cobre tabelas simples, onde os resultados são razoavelmente previsíveis. Em uma tabela simples, toda célula ocupa somente uma linha e coluna. Você pode usar CSS para tabelas complexas onde células expandam (extendam-se sobre) mais do que uma linha ou coluna, mas tabelas como estas estão fora do escopo deste tutorial básico.

+ +

Bordas

+ +

Células não têm margens.

+ +

Células têm bordas e enchimento. Por padrão, as bordas são separadas pelo valor da propriedade border-spacing da tabela. Você pode também remover o espaçamento completamente configurando a propriedade border-collapse da tabela para collapse.

+ + + + + + + + +
Exemplo
Aqui estão três tabelas. +

A tabela da esquerda tem espaçamento de borda 0.5 em. A tabela do centro tem espaçamento da borda zero. A tabela da direita tem bordas unidas:

+ + + + + + + + + +
+ + + + + + + + + + + +
PausCopas
OurosEspadas
+
+ + + + + + + + + + + +
PausCopas
OurosEspadas
+
+ + + + + + + + + + + +
PausCopas
OurosEspadas
+
+
+ +

Subtítulos

+ +

Um subtítulo é uma etiqueta que se aplica à tabela inteira. Por padrão, isto é mostrado no topo da tabela.

+ +

Para mover isto para o fim, configure a propriedade caption-side para bottom. A propriedade é herdada, então alternativamente você pode configurar isto na tabela em outro elemento ascendente.

+ +

Para estilizar o texto do subtítulo, use qualquer das propriedades usuais para texto.

+ + + + + + + + +
Exemplo
Esta tabela tem um subtítulo no fim: +
+
+#demo-table > caption {
+  caption-side: bottom;
+  font-style: italic;
+  text-align: right;
+  }
+
+
+ + + + + + + +
+ + + + + + + +
Naipes
+ + + + + + + + + + + +
PausCopas
OurosEspadas
+
+
+
+ +

Células vazias

+ +

Você pode exibir células vazias (isto é, suas bordas e fundos) especificando empty-cells: show; para o elemento da tabela.

+ +

Você pode escondê-los especificando empty-cells:hide;. Então, se um elemento principal tem um fundo e o chama, isto mostra através da célula vazia.

+ + + + + + + + +
Exemplo
Estas tabelas tem um fundo de verde pálido. Suas células tem um fundo de cinza pálido e bordas de cinza escuro. +

Na esquerda da tabela, a célula vazia é mostrada. Na direita, é escondida:

+ + + + + + + + +
+ + + + + + + + + + + +
 Copas
OurosEspadas
+
+ + + + + + + + + + + +
 Copas
OurosEspadas
+
+
+ + + + + + + + +
Mais detalhes
Para informações detalhasdas sobre tabelas, veja Tables em CSS Specification. +

A informação lá vai além do que há neste tutorial, mas não cobre as diferenças entre os navegadores que podem afetar tabelas complexas.

+
+ +

Ação: Estilizando uma tabela

+ +

Faça um novo documento HTML, doc3.html. Copie e cole o conteúdo daqui, tendo certeza que você rolou a tela para pegar tudo isto:

+ +
+
<DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<HTML>
+<HEAD>
+<TITLE>Documento de amostra 3</TITLE>
+<LINK rel="stylesheet" type="text/css" href="style3.css">
+</HEAD>
+<BODY>
+
+<TABLE id="demo-table">
+<CAPTION>Oceanos</CAPTION>
+
+<THEAD>
+<TR>
+<TH></TH>
+<TH>Área</TH>
+<TH>Profundidade Média</TH>
+</TR>
+<TR>
+<TH></TH>
+<TH>milhões de km<SUP>2</SUP></TH>
+<TH>m</TH>
+</TR>
+</THEAD>
+
+<TBODY>
+<TR>
+<TH>Ártico</TH>
+<TD>13,000</TD>
+<TD>1,200</TD>
+</TR>
+<TR>
+<TH>Atlântico</TH>
+<TD>87,000</TD>
+<TD>3,900</TD>
+</TR>
+<TR>
+<TH>Pacífico</TH>
+<TD>180,000</TD>
+<TD>4,000</TD>
+</TR>
+<TR>
+<TH>Índico</TH>
+<TD>75,000</TD>
+<TD>3,900</TD>
+</TR>
+<TR>
+<TH>Antártico</TH>
+<TD>20,000</TD>
+<TD>4,500</TD>
+</TR>
+</TBODY>
+
+<TFOOT>
+<TR>
+<TH>Total</TH>
+<TD>361,000</TD>
+<TD></TD>
+</TR>
+<TR>
+<TH>Média</TH>
+<TD>72,000</TD>
+<TD>3,800</TD>
+</TR>
+</TFOOT>
+
+</TABLE>
+
+</BODY>
+</HTML>
+
+
+ +

Crie uma nova folha de estilo, style3.css. Copie e cole o conteúdo daqui, tendo certeza que você rolou a tela para pegar tudo isto:

+ +
+
/*** Estilo para doc3.html (Tabelas) ***/
+
+#demo-table {
+  font: 100% sans-serif;
+  background-color: #efe;
+  border-collapse: collapse;
+  empty-cells: show;
+  border: 1px solid #7a7;
+  }
+
+#demo-table > caption {
+  text-align: left;
+  font-weight: bold;
+  font-size: 200%;
+  border-bottom: .2em solid #4ca;
+  margin-bottom: .5em;
+  }
+
+
+/* basic shared rules */
+#demo-table th,
+#demo-table td {
+  text-align: right;
+  padding-right: .5em;
+  }
+
+#demo-table th {
+  font-weight: bold;
+  padding-left: .5em;
+  }
+
+
+/* header */
+#demo-table > thead > tr:first-child > th {
+  text-align: center;
+  color: blue;
+  }
+
+#demo-table > thead > tr + tr > th {
+  font-style: italic;
+  color: gray;
+  }
+
+/* fix size of superscript */
+#demo-table sup {
+  font-size: 75%;
+  }
+
+/* body */
+#demo-table td {
+  background-color: #cef;
+  padding:.5em .5em .5em 3em;
+  }
+
+#demo-table tbody th:after {
+  content: ":";
+  }
+
+
+/* footer */
+#demo-table tfoot {
+  font-weight: bold;
+  }
+
+#demo-table tfoot th {
+  color: blue;
+  }
+
+#demo-table tfoot th:after {
+  content: ":";
+  }
+
+#demo-table > tfoot td {
+  background-color: #cee;
+  }
+
+#demo-table > tfoot > tr:first-child td {
+  border-top: .2em solid #7a7;
+  }
+
+
+ +

Abra o documento no seu navegador. Deve ser muito similar a este:

+ + + + + + + +
+
+

Oceanos

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 ÁreaProfundidade média
 milhões de km2m
Ártico:13,0001,200
Atlântico:87,0003,900
Pacífico:180,0004,000
Índico:75,0003,900
Antártico:20,0004,500
Total:361,000 
Média:72,0003,800
+
+
+
+ +

Compare estas regras em sua folha de estilo com a tabela exibida, para se assegurar de que entende o efeito de cada regra. Se você achou uma regra com a qual não está seguro sobre, descomente-a e atualize o navegador para ver o que acontece.

+ +

Aqui estão algumas notas sobre esta tabela:

+ + + + + + + + + + +
Desafios
Mude a folha de estilo para fazer a tabela parecer com isto: + + + + + + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 ÁreaProfundidade média
 milhões de km2m
Ártico:13,0001,200
Atlântico:87,0003,900
Pacífico:180,0004,000
Índico:75,0003,900
Antártico:20,0004,500
Total:361,000 
Média:72,0003,800
+
+ +

Oceanos

+
+
+
+ +

O que vem depois?

+ +

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor combribua nesta página de Discussão.

+ +

Esta é a última página deste tutorial que foca as propriedades e valores das CSS. Para um sumário completo de propriedades e valores, veja Full property table em CSS Specification.

+ +

A próxima página mostra novamente o propósito e a estrutura das folhas de estilo CSS: Mídia

+ +

{{ PreviousNext("CSS:Como começar:Disposição", "CSS:Como começar:Mídia") }}

diff --git a/files/pt-pt/learn/css/building_blocks/values_and_units/index.html b/files/pt-pt/learn/css/building_blocks/values_and_units/index.html new file mode 100644 index 0000000000..d5c15375d7 --- /dev/null +++ b/files/pt-pt/learn/css/building_blocks/values_and_units/index.html @@ -0,0 +1,341 @@ +--- +title: Cor +slug: Web/CSS/Como_começar/Cor +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Introduction_to_CSS/Values_and_units#Colors +translation_of_original: Web/Guide/CSS/Getting_started/Color +--- +

{{ PreviousNext("CSS:Como começar:Estilos de texto", "CSS:Como começar:Conteúdo") }}

+ +

Esta página explica mais sobre como você pode especificar cores no CSS.

+ +

Em sua folha de estilo de amostra, você é introduzido nas cores de fundo.

+ +

Informação: Cor

+ +

Neste tutorial até agora, você usou um limitado número de cores nomeadas. CSS 2 suporta ao todo 17 cores nomeadas. Alguns dos nomes podem não ser o que você espera:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 black gray silver white 
primáriasred lime blue 
secundáriasyellow aqua fuchsia 
 maroon orange olive purple green navy teal 
+ +

 

+ + + + + + + + +
Mais detalhes
Seu navegador pode suportar muitas cores nomeadas, como: + + + + + + + + + + + + + + + +
dodgerblue peachpuff tan firebrick aquamarine 
+ +

Para detalhes sobre esta lista extendida, veja: SVG color keywords no CSS 3 Color Module. Cuidado ao usar cores nomeadas, pois seu navegador pode não suportar.

+
+ +


+ Para uma paleta maior, específica de cores de componentes vermelho, verde ou azul você precisa usar um sinal numérico (#) e três digitos hexadecimais na faixa de 0 – 9 e a – f. As letras a – f representam os valores 10 – 15:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
black #000
pure red #f00
pure green #0f0
pure blue #00f
white #fff
+ +


+ Para a paleta total, especifique dois digitos hexadecimais por cada componente:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
black #000000
pure red #ff0000
pure green #00ff00
pure blue #0000ff
white #ffffff
+ +

Você pode usualmente pegar estes seis digitos em código hexadeximal de seu programa de imagens ou alguma outra ferramenta.

+ + + + + + + + + + + +
Exemplos
Com uma pequena prática, você pode ajustar as cores de três digitos manualmente para a maioria dos propósitos: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Começe com vermelho puro: #f00
Para tornar isto mais pálido, adicione um pouco de verde e azul: #f77
Para tornar isto mais alaranjado, adicione um pouquinho mais de verde: #fa7
Para tornar isto mais escuro, reduza todos os componentes: #c74
Para reduzir a saturação, faça os componentes mais parecidos: #c98
Se você quiser deixar todos os componentes iguais, você obterá cinza: #ccc
+
Para uma sombra pastel como azul pálido: + + + + + + + + + + + + + +
Começe com branco puro: #fff
Reduza um pouco os outros componentes: #eef
+
+ + + + + + + + +
Mais detalhes
Você pode também especificar uma cor usando valores decimais RGB na faixa de 0 – 255, ou porcentagens. +

Por exemplo, este marrom (vermelho escuro):

+ +
+
+rgb(128, 0, 0)
+
+
+ +


+ Para maiores detalhes sobre como especificar cores, veja: Colors na CSS Specification.

+ +

Para informação sobre sistema de cores combinadas como o Menu and ThreeDFace, veja: CSS2 System Colors na CSS Specification.

+
+ +

Propriedades de cor

+ +

Você já usou a propriedade color para textos.

+ +

Você também já usou a propriedade background-color para mudar elementos de fundo.

+ +

Fundos podem ser configurados para transparent para remover qualquer cor explicitamente, reavaliando os elementos principais do fundo.

+ + + + + + + + +
Exemplo
As caixas de Exemplo neste tutorial usam este fundo amarelo pálido: +
+
+background-color: #fffff4;
+
+
+ +

As caixas de Mais detalhes usam esta paleta cinza:

+ +
+
+background-color: #f4f4f4;
+
+
+
+ +

Ação: Usando códigos de cor

+ +

Edite seu arquivo CSS. Faça a mudança mostrada aqui em negrito, para dar às letras iniciais um fundo azul pálido. (O layout e os comentários no seu arquivo irão provavelmente diferir do arquivo mostrado aqui. Mantenha o layout e os comentários como você preferir.)

+ +
+
/*** CSS Tutorial: Página de Cor ***/
+
+/* Fonte da Página */
+body {font: 16px "Comic Sans MS", cursive;}
+
+/* Parágrafos */
+p {color: blue;}
+#first {font-style: italic;}
+
+/* Letras Iniciais */
+strong {
+  color: red;
+  background-color: #ddf;
+  font: 200% serif;
+  }
+
+.carrot {color: red;}
+.spinach {color: green;}
+
+
+ +

Atualize seu navegador para ver o resultado:

+ + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ + + + + + + + +
Desafio
No seu arquivo CSS, mude todos os nomes das cores para o código de cor com três digitos sem afetar o resultado. +

(Isto não pode ser feito exatamente, mas você pode deixar parecido. Para fazer isso exatamente você precisa do código com seis dígitos, e você precisa olhar a Especificação CSS ou usar uma ferramenta gráfica para converter as cores.)

+
+ +

O que vem depois?

+ +

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

+ +

Seu documento de amostra e sua folha de estilo de amostra separam rigorosamente o conteúdo do estilo.

+ +

A próxima página explica como você pode fazer exceções para separar rigorosamente: Conteúdo

+ +

{{ PreviousNext("CSS:Como começar:Estilos de texto", "CSS:Como começar:Conteúdo") }}

diff --git a/files/pt-pt/learn/css/css_layout/index.html b/files/pt-pt/learn/css/css_layout/index.html new file mode 100644 index 0000000000..0612aad9b5 --- /dev/null +++ b/files/pt-pt/learn/css/css_layout/index.html @@ -0,0 +1,453 @@ +--- +title: Disposição +slug: Web/CSS/Como_começar/Disposição +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/CSS_layout +translation_of_original: Web/Guide/CSS/Getting_started/Layout +--- +

{{ PreviousNext("CSS:Como começar:Caixas", "CSS:Como começar:Tabelas") }}

+ +

Esta página descreve algumas maneiras para ajustar a disposição do seu documento.

+ +

Você muda a disposição do seu documento de amostra...

+ +

Informação: Disposição

+ +

Você pode usar as CSS para especificar vários efeitos visuais que mudam a disposição do seu documento. Algumas técnicas para especificação da disposição são avançadas,e além do alcance deste tutorial básico.

+ +

Quando você desenha uma disposição que aparece similar em vários navegadores, sua folha de estilo interage com a folha de estilo padrão do navegador e o motor de disposição em alguns caminhos pode se tornar complexo. Isto é também uma matéria avançada, além do alcance deste tutorial básico.

+ +

Esta página descreve algumas técnicas simples que você pode tentar.

+ +

Estrutura do documento

+ +

Se você quer controlar a disposição do seu documento, então você pode ter que mudar sua estrutura.

+ +

A linguagem de marcação do seu documento pode ter tags com propósito geral para criar a estrutura. Por exemplo, no HTML você pode usar a tag DIV para criar a estrutura.

+ + + + + + + + +
Exemplo
No seu documento de amostra, os parágrafos numerados sob o segundo título não tem um "recipiente" próprio. +

Sua folha de estilo não pode desenhar uma borda ao redor destes parágrafos, porque não há elemento especificado no seletor.

+ +

Para fixar este problema estrutural, você pode adicionar uma tag DIV em torno dos parágrafos. Esta tag é única, então isto pode ser identificado por um atributo id:

+ +
+
+<H3 class="numbered">Parágrafos numerados</H3>
+<DIV id="numbered">
+<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>
+</DIV>
+
+
+ +

Agora sua folha de estilo pode use uma regra para especificar bordas em tordo de ambas as listas:

+ +
+
+ul, #numbered {
+  border: 1em solid #69b;
+  padding-right:1em;
+  }
+
+
+ +

O resultado deve ser como este:

+ + + + + + + +
+

(A) Os oceanos

+ +
+
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+
+ +

(B) Parágrafos numerados

+ +
+

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+
+
+ +

Tamanhos das unidades

+ +

Anteriormente neste tutorial, você especificou tamanhos em pixels (px). Estes são apropriados para alguns propósitos em um dispositivo de exposição como uma tela de computador. Mas quando o usuário muda o tamanho da fonte, sua disposição pode ficar errada.

+ +

Para muitos propósitos é melhor especificar tamanhos com porcentagem ou em ems (em). Um em é nominalmente o tamanho da fonte corrente (a largura de uma letra m). Quando o usuário muda o tamanho da fonte, sua disposição ajusta-se automaticamente.

+ + + + + + + + +
Exemplo
A borda da esquerda deste texto tem o tamanho especificado em pixels. +

A borda da direita tem o tamanho especificado em ems. No seu navegador, mude o tamanho da fonte para ver como a borda da direita se ajusta mas a borda da esquerda não:

+ + + + + + + +
+
Redimensione-me por favor
+
+
+ + + + + + + + +
Mais detalhes
Para outros dispositivos, outras unidades de comprimento são apropriadas. +

Há mais informação sobre isto em uma página anterior deste tutorial.

+ +

Para detalhes completos sobre os valores e unidades que você pode usar, veja Values em CSS Specification.

+
+ +

Disposição do texto

+ +

Duas propriedades especificam como o conteúdo de um elemento é alinhado. Você pode usá-las para ajustes simples na disposição:

+ + + +
+
Alinha o conteúdo. Use um destes valores: left, right, center, justify
+
+ + + +
+
Indenta o conteúdo, colocando o espaço que você especificar.
+
+ +

Estas propriedades aplicam-se a qualquer conteúdo como texto no elemento, não somente ao texto atual. Lembre-se que elas são herdadas pelo elemento filho, então você pode ter que desativá-las nos elementos filhos para não se surpreender com os resultados.

+ + + + + + + + +
Exemplo
Para centralizar títulos: +
+
+h3 {
+  border-top: 1px solid gray;
+  text-align: center;
+  }
+
+
+ +

Resulta em:

+ + + + + + + +
+

(A) Os oceanos

+
+ +

Em um documento HTML, o conteúdo que você vê abaixo do título não é contido estruturalmente pelo título. Então quando você alinha um título como isto, as tags abaixo do título não são afetadas pela herança.

+
+ +

Flutuantes

+ +

A propriedade float força um elemento para a esquerda ou direita. Isto é uma maneira simples de controlar sua posição e tamanho.

+ +

O resto do conteúdo do documento normalmente flui ao redor do elemento flutuado. Você pode controlar isto usando a propriedade clear em outros elementos para fazê-los permanecer sem flutuantes.

+ + + + + + + + +
Exemplo
Em seu documento de amostra, as listas esticam através da janela. Você pode prevenir isto flutuando-os para a esquerda. +

Para manter os títulos no lugar, você precisa também especificar que eles permaneçam limpos de flutuantes à sua esquerda:

+ +
+
+ul, #numbered {float: left;}
+h3 {clear: left;}
+
+
+ +

O resultado deve se parecer com isto:

+ + + + + + + +
+

(A) Os oceanos

+ +
+
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+
+ +

(B) Parágrafos numerados

+ +
+

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+
+ +

(Um pequeno enchimento é necessário à direita das caixas, onde a borda fica muito perto do texto.)

+
+ +

Posicionamento

+ +

Você pode especificar a posição dos elementos de quatro maneiras, especificando a propriedade position e um dos valores seguintes:

+ +

Estas são propriedades avançadas. É possível usá-las de maneiras simples — esta é a razão pela qual elas são mencionadas neste tutorial básico. Mas usando-as para disposições complexas pode-se dificultar.

+ + + +
+
A posição do elemento é alterada relativamente à sua posição normal.
+
Use-o para mover um elemento por uma quantidade especificada. Às vezes você pode usar a margem do elemento para obter o mesmo efeito.
+
+ + + +
+
A posição do elemento é fixa.
+
Especifique a posição do elemento relativa à janela do documento. Mesmo que o resto do documento seja rolado, o elemento permanece fixo.
+
+ + + +
+
A posição do documento é fixada relativamente a um elemento pai.
+
Somente um elemento pai que esteja posicionado com relative, fixed ou absolute o fará.
+
+ +
+
Você pode tornar qualquer elemento principal apropriado, especificando position: relative; sem especificar qualquer movimento.
+
+ + + +
+
O padrão. Use este valor caso precise desativar a posição explicitamente.
+
+ +

Agora, com estes valores da propriedade position (exeto para static), especifique uma ou mais propriedades: top, right, bottom, left, width, height para identificar onde você quer que o elemento apareça, e talvez também seu tamanho.

+ + + + + + + + +
Exemplo
Para posicionar dois elementos no topo, crie um "recipiente" principal em seu documento com os dois elementos dentre dele: +
+
+<DIV id="parent-div">
+<P id="forward">/</P>
+<P id="back">\</P>
+</DIV>
+
+
+ +

Na sua folha de estilo, faça a posição principal relative. Ela não precisa que seja especificado qualquer movimento atual. Faça a posição subordinada absolute:

+ +
+
+#parent-div {
+  position: relative;
+  font: bold 200% sans-serif;
+  }
+
+#forward, #back {
+  position: absolute;
+  margin:0px;
+  top: 0px;
+  left: 0px;
+  }
+
+#forward {
+  color: blue;
+  }
+
+#back {
+  color: red;
+  }
+
+
+ +

O resultado deve ser como isto, com a contra barra (\) sobre a barra (/):

+ +
+

/

+ +

\

+
+ + + + + + + +
 
+ +

 

+
+ + + + + + + + +
Mais detalhes
A história completa sobre posicionamento toma dois complexos capítulos em CSS Specification: Visual formatting model e Visual formatting model details. +

Se você está desenhando folhas de estilo para trabalharem em vários navegadores, então você também precisa levar em conta as diferenças na maneira em que os navegadores interpretam o padrão, e talvez bugs em algumas versões de alguns navegadores.

+
+ +

Ação: Especificando a disposição

+ +

Mude seu documento de amostra e sua folha de estilo usando os exemplos anteriores nas seções Estrutura do documento e Flutuantes.

+ +

No exemplo dos Flutuantes, adicione enchimento para separar o texto da borda direita por 0,5 em.

+ + + + + + + + +
Desafio
Mude seu documento de amostra, adicionando esta tag perto do fim, somente antes de </BODY> +
+<IMG id="fixed-pin" src="Yellow-pin.png" alt="Yellow map pin">
+
+ +

Se você não baixou o arquivo de imagem anteriormente neste tutorial, baixe-o agora:

+ + + + + + + +
Image:Yellow-pin.png
+ +

Prediga onde a imagem irá aparecer no seu documento. Então atualize seu navegador para ver se você estava certo.

+ +

Adicione uma regra à sua folha de estilo que fixe a imagem no topo e a direita do seu documento.

+ +

Atualize seu navegador e diminua o tamanho da janela. Cheque se a imagem permanece no topo e a direita mesmo que você role seu documento:

+ +
+
+

(A) Os oceanos

+ +
+
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+
+ +

(B) Parágrafos numerados

+ +
+

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+ +

 

+ +
Yellow map pin
+
+
+
+ +

O que vem depois?

+ +

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

+ +

A próxima página descreve seletores para regras mais avançadas das CSS, e algumas maneiras específicas de estilizar tabelas: Tabelas

+ +

{{ PreviousNext("CSS:Como começar:Caixas", "CSS:Como começar:Tabelas") }}

diff --git a/files/pt-pt/learn/css/estilo_de_texto/index.html b/files/pt-pt/learn/css/estilo_de_texto/index.html deleted file mode 100644 index 5d00bc90c5..0000000000 --- a/files/pt-pt/learn/css/estilo_de_texto/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Estilizar texto -slug: Learn/CSS/Estilo_de_texto -tags: - - CSS - - Hiperligações - - Principiante - - Texto - - Tipos de Letra - - letra - - lina - - listas - - modulo - - sombra - - tipo de letra - - tipos de letra da Web -translation_of: Learn/CSS/Styling_text ---- -
{{LearnSidebar}}
- -

Com os conceitos básicos da linguagem CSS cobertos, o próximo tópico de CSS para se concentrar será o estilo de texto - uma das coisas mais comuns que irá fazer com CSS. Aqui, nós vamos ver os fundamentos do estilo de texto, incluindo a configuração do tipo de letra, negrito, itálico, espaçamento de linha e letra, sombras e outros recursos de texto. Nós completamos o módulo ao analisar a aplicação de tipos de letra personalizadas para a sua página, e listas de estilo e hiperligações.

- -

Pré-requisitos

- -

Before starting this module, you should already have basic familiarity with HTML, as discussed in the Introduction to HTML module, and be comfortable with CSS fundamentals, as discussed in Introduction to CSS.

- -
-

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin, CodePen or Thimble.

-
- -

Guias

- -

This module contains the following articles, which will teach you all of the essentials behind styling HTML text content.

- -
-
Fundamental text and font styling
-
In this article we go through all the basics of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.
-
Styling lists
-
Lists behave like any other text for the most part, but there are some CSS properties specific to lists that you need to know about, and some best practices to consider. This article explains all.
-
Styling links
-
When styling links, it is important to understand how to make use of pseudo-classes to style link states effectively, and how to style links for use in common varied interface features such as navigation menus and tabs. We'll look at all these topics in this article.
-
Web fonts
-
Here we will explore web fonts in detail — these allow you to download custom fonts along with your web page, to allow for more varied, custom text styling.
-
- -

Avaliações

- -

The following assessments will test your understanding of the text styling techniques covered in the guides above.

- -
-
Typesetting a community school homepage
-
In this assessment we'll test your understanding of styling text by getting you to style the text for a community school's homepage.
-
- -
- - - - - -
diff --git a/files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html b/files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html new file mode 100644 index 0000000000..08ede46aa3 --- /dev/null +++ b/files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html @@ -0,0 +1,188 @@ +--- +title: CSS legível +slug: Web/CSS/Como_começar/CSS_legível +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Introduction_to_CSS/Syntax#Beyond_syntax_make_CSS_readable +translation_of_original: Web/Guide/CSS/Getting_started/Readable_CSS +--- +

{{ PreviousNext("CSS:Como começar:Seletores", "CSS:Como começar:Estilos de texto") }}

+ +

Esta página discute o estilo e a gramática da linguagem CSS.

+ +

Você muda a maneira em que seu arquivo de amostra CSS é exibido, para torná-lo mais legível.

+ +

Informação: CSS legível

+ +

Você pode adicionar espaço em branco e comentários na sua folha de estilo para fazê-la mais legível. Você pode também juntar seletores de grupo, quando as mesmas regras de estilo se aplicam aos elementos selecionados em meios diferentes.

+ +

Espaço em branco

+ +

Espaços em branco significam espaços reais, tabs e quebras de linha. Você pode adicionar espaços em branco para tornar suas folhas de estilo mais legíveis.

+ +

Seu arquivo de amostra de CSS atualmente tem uma regra por linha, e quase o mínimo de espaço em branco. Em uma uma folha de estilo complexa esta disposição pode dificultar a leitura, dificultando também a manutenção da sua folha de estilo.

+ +

A disposição que você escolhe é usualmente um preferência pessoal, mas se suas folhas de estilo são parte de projetos compartilhados, estes projetos podem ter suas próprias convenções.

+ + + + + + + + +
Exemplos
Algumas pessoas gostam de uma diposição compacta que temos usado, somente dividindo a linha quando ela se torna muito longa: +
+.carrot {color: orange; text-decoration: underline; font-style: italic;}
+
+ +

Algumas pessoas preferem uma propriedade-valor por linha:

+ +
+
+.carrot
+{
+color: orange;
+text-decoration: underline;
+font-style: italic;
+}
+
+
+ +

Algumas pessoas usam tabs – dois espaços, quatro espaços, ou um tab são comuns:

+ +
+
+.carrot {
+  color: orange;
+  text-decoration: underline;
+  font-style: italic;
+}
+
+
+ +

Algumas pessoas gostam de enfileirar a linha verticalmente (mas é difícil de manter uma disposição assim):

+ +
+
+.carrot
+    {
+    color           : orange;
+    text-decoration : underline;
+    font-style      : italic;
+    }
+
+
+ +

Algumas pessoas usam tabs para a disposição. Algumas pessoas usam somente espaços.

+
+ +

Comentários

+ +

Comentários em CSS começam com /* e terminam com */.

+ +

Você pode usar comentários para fazer comentários reais na sua folha de estilo, e também para descomentar partes que estiverem temporariamente para propósito de testes.

+ +

Para comentar parte da folha de estilo, coloque a parte em um comentário então o navegador ignorará isso. Tome cuidado onde você começa e termina o seu comentário. O resto da sua folha de estilo ainda deve ter a sintaxe correta.

+ + + + + + + + +
Exemplo
+
+
+/* Estilo para a letra C inicial no primeiro parágrafo */
+.carrot {
+  color:            orange;
+  text-decoration:  underline;
+  font-style:       italic;
+  }
+
+
+
+ +

Seletores agrupados

+ +

Quando muitos elementos tiverem o mesmo estilo, você pode especificar um grupo de seletores, separando-os com comentários. A declaração se aplica a todos os elementos selecionados.

+ +

Em outra parte da sua folha de estilo você pode especificar os mesmos seletores, de novo individualmente, para aplicar estilo individual às suas regras.

+ + + + + + + + +
Exemplo
Esta regra faz os elementos H1, H2 and H3 da mesma cor. +

Isto é conveniente para especificar a cor em somente um lugar, no caso em que precisa ser alterado.

+ +
+
+/* cores para os cabeçalhos */
+h1, h2, h3 {color: navy;}
+
+
+
+ +

Ação: Adicionando comentários e melhorando o arranjo

+ +

Edite seu arquivo CSS, e assegure-se que ele tem todas as regras nele (em qualquer ordem):

+ +
+
strong {color: red;}
+.carrot {color: orange;}
+.spinach {color: green;}
+#first {font-style: italic;}
+p {color: blue;}
+
+
+ +

Faça isto mais legível rearranjando isto em um meio que possa ser achado lógicamente, adicionando espaços em branco e comentários da maneira que você achar melhor.

+ +

Salve o arquivo e atualize a tela do seu navegador, assegure-se que as mudanças que você fez não afetaram o modo como a folha de estilo trabalha:

+ + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ + + + + + + + +
Desafio
Comente parte de sua folha de estilo, sem mudar qualquer coisa, para fazer a primeira letra de seu documento vermelha: + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ +

(Existe mais de uma maneira de fazer isto.)

+
+ +

O que vem depois?

+ +

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

+ +

Seu documento de amostra usou o texto em itálico e o texto com sublinhado. A próxima página descreve mais caminhos para especificar a aparência do texto no seu documento: Estilos de texto

+ +

{{ PreviousNext("CSS:Como começar:Seletores", "CSS:Como começar:Estilos de texto") }}

diff --git a/files/pt-pt/learn/css/first_steps/how_css_works/index.html b/files/pt-pt/learn/css/first_steps/how_css_works/index.html new file mode 100644 index 0000000000..bd667439ff --- /dev/null +++ b/files/pt-pt/learn/css/first_steps/how_css_works/index.html @@ -0,0 +1,130 @@ +--- +title: Como o CSS trabalha +slug: Web/CSS/Como_começar/Como_o_CSS_trabalha +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/First_steps/How_CSS_works +translation_of_original: Web/Guide/CSS/Getting_started/How_CSS_works +--- +

{{ PreviousNext("CSS:Como começar:Porque usar CSS", "CSS:Como começar:Cascata e herança") }}

+ +

Esta página explica como o CSS trabalha no seu navegador. Você analiza seu documento de amostra, reavaliando os detalhes do seu estilo.

+ +

Informação: Como o CSS trabalha

+ +

Quando o Mozilla exibe um documento, é necessário combinar o conteúdo do documento com seu estilo de informação. Então o documento é processado em dois estágios:

+ + + + + +

Uma linguagem de marcação usa tags para definir a estrutura do documento. Uma tag pode armazenar outras tags entre seu início e fim.

+ +

Um DOM tem a estrutura como a de uma árvore. Cada tag e período do texto na linguagem de marcação torna-se um na estrutura da árvore. Os nós do DOM não são armazenadores. Em substituição, eles são primários aos nós subordinados.

+ +

Os nós que correspondem a tags também são conhecidos por elementos.

+ + + + + + + + +
Exemplo
No seu documento de amostra, a tag <p> e seu fim </p> criam um armazenamento: +
+
+<p>
+  <strong>C</strong>ascading
+  <strong>S</strong>tyle
+  <strong>S</strong>heets
+</p>
+
+
+ +

No DOM, o corespondente ao nó P é um primário. Os subordinados são os nós STRONG e os nós do texto. Os nós STRONG são os primários, e os nós do texto são os subordinados.

+ +
+

P ├─STRONG │ │ │ └─"C"
+ │
+ ├─"ascading"
+ │
+ ├─STRONG │ │ │ └─"S"
+ │
+ ├─"tyle"
+ │
+ ├─STRONG │ │ │ └─"S"
+ │
+ └─"heets"

+
+
+ +

O entendimento do DOM ajuda-o a projetar, depurar e manter seu CSS, pois o DOM é onde o seu CSS e o conteúdo do documento se unem.

+ +

Ação: Analizando um DOM

+ +

Para analizar um DOM, você precisa de um software especial. Aqui, você usa o DOM Inspector (DOMi) da Mozilla para analizar um DOM.

+ +

Use seu navegador Mozilla para abrir seu documento simples.

+ +

Na barra de menu do seu navegador, escolha Ferramentas – DOM Inspector, ou talvez Ferramentas – Desenvolvimento Web – DOM Inspector.

+ + + + + + + + +
Mais detalhes
Se seu navegador Mozilla não tem o DOMi, você pode reinstalá-lo assegurando-se de escolher para instalar o componente de ferramentas da web. Então retorne a este tutorial. +

Se você não quiser instalar o DOMi, você pode pular esta seção e ir diretamente para a próxima página. Pulando esta seção você não interfere com o resto deste tutorial.

+
+ +


+ No DOMi, expanda os nós do seu documento clicando em suas flechas.

+ +

Nota: O espaçamento em seu arquivo HTML faz com que o DOMi mostre alguns nós de texto vazios, que você pode ignorar.

+ +

O resultado deve ser parecido com isto, dependendo do que você tenha expandido:

+ + + + + + + +
+
+


+ P │ │ │ STRONG │ │ └#text │ ├╴#textSTRONG │ │

+
+
+ +

Quando você seleciona algum nó, você pode usar o painel direito do DOMi para achar mais sobre ele. Por exemplo, quando você seleciona um nó do texto, DOMi mostra para você o texto no painel da direita.

+ +

Quando você seleciona um elemento nó, DOMi o analiza e fornece uma enorme quantidade de informações no seu painel direito. A informação sobre estilo é somente uma parte das informações que ele fornece.

+ + + + + + + + +
Desafio
No DOMi, clique no nó STRONG. +

Use o painel direito do DOMi para achar onde fica a cor do nó (vermelho) e onde sua aparência é mais forte que o texto normal (negrito).

+
+ +

O que vem depois?

+ +

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

+ +

Se você tomou o desafio, você viu o estilo da informação em mais de um lugar interagir para criar o estilo final para um elemento.

+ +

A próxima página explica mais sobre estas interações: Cascata e herança

+ +

{{ PreviousNext("CSS:Como começar:Porque usar CSS", "CSS:Como começar:Cascata e herança") }}

diff --git a/files/pt-pt/learn/css/first_steps/index.html b/files/pt-pt/learn/css/first_steps/index.html new file mode 100644 index 0000000000..fa514756bd --- /dev/null +++ b/files/pt-pt/learn/css/first_steps/index.html @@ -0,0 +1,92 @@ +--- +title: Como começar +slug: Web/CSS/Como_começar +tags: + - CSS + - 'CSS:Como_começar' + - Todas_as_Categorias +translation_of: Learn/CSS/First_steps +translation_of_original: Web/Guide/CSS/Getting_started +--- +

 

+ +

Introdução

+ +

Este tutorial o introduz às CSS (Cascading Style Sheets - Folhas de Estilo em Cascata).

+ +

Este tutorial o orienta nos recursos básicos de CSS com exemplos práticos que você pode experimentar sozinho em seu computador. Ele é dividido em duas partes:

+ + + + + +

Este tutorial é baseado na CSS 2.1 Specification.

+ +

Quem deve ler este tutorial?

+ +

Este tutorial é direcionado para iniciantes em CSS, mas você também poderá usá-lo caso tenha alguma experiência em CSS.

+ +

Se você é um iniciante em CSS, leia a Parte I deste tutorial para entender CSS e aprender a usá-lo. Em seguida, leia a Parte II para entender o escopo de CSS no Mozilla.

+ +

Se você conhece CSS, poderá ignorar as partes desse tutorial que já conhece e ler apenas as partes que lhe interessam.

+ +

Se você já tem experiência em CSS mas não no Mozilla, pode ir direto para a Parte II.

+ +

O que você precisa antes de começar?

+ +

Para melhor aproveitar este tutorial, você precisa de um editor de arquivos de texto e um navegador Mozilla (Firefox, Mozilla Suite ou Seamonkey). Você também deve saber como utilizá-los de um modo básico.

+ +

Se não deseja editar arquivos, você pode apenas ler o tutorial e observar as imagens, mas este não é o melhor modo de aprendizado.

+ +

Poucas partes deste tutorial podem requerer outro software Mozilla. Essas partes são opcionais. Você pode ignorar essas partes se não desejar fazer o download de outro software Mozilla.

+ +

Nota: As CSS oferece modos de se trabalhar com cores, de modo que partes deste tutorial dependem de cores. Você poderá utilizar essas partes facilmente somente se tiver um monitor colorido e uma visão colorida normal.

+ +

Como utilizar este tutorial

+ +

Para utilizar este tutorial, leia cuidadosamente as páginas e em seqüência. Se perder uma página, você poderá ter dificuldades para entender as páginas posteriores.

+ +

Em cada página, utilize a seçãoInformações para entender como o CSS funciona. Utilize a seçãoAções para tentar usar o CSS em seu próprio computador.

+ +

Para testar seus conhecimentos, faça o teste ao final de cada página. As soluções para alguns testes são reveladas nas páginas posteriores no tutorial.

+ +

Para se aprofundar em CSS, leia as informações nas caixas entituladasMais detalhes. Utilize os links para localizar informações referentes às CSS.

+ +

Tutorial Parte I

+ +

Um guia passo-a-passo para CSS.

+ +
    +
  1. O que é CSS
  2. +
  3. Porque usar CSS
  4. +
  5. Como o CSS trabalha
  6. +
  7. Cascata e herança
  8. +
  9. Seletores
  10. +
  11. CSS legível
  12. +
  13. Estilos de texto
  14. +
  15. Cor
  16. +
  17. Conteúdo
  18. +
  19. Listas
  20. +
  21. Caixas
  22. +
  23. Disposição
  24. +
  25. Tabelas
  26. +
  27. Média
  28. +
+ +

Tutorial Parte II

+ +

Exemplos que mostram o escopo da CSS no Mozilla.

+ +
    +
  1. JavaScript
  2. +
  3. XBL bindings
  4. +
  5. Interfaces de usuário XUL
  6. +
  7. Gráficos SVG
  8. +
  9. Dados XML
  10. +
+ +

{{ languages( { "en": "en/CSS/Getting_Started", "fr": "fr/CSS/Premiers_pas", "it": "it/Conoscere_i_CSS", "ja": "ja/CSS/Getting_Started", "nl": "nl/CSS/Voor_Beginners", "pl": "pl/CSS/Na_pocz\u0105tek", "zh-cn": "cn/CSS/\u5f00\u59cb" } ) }}

diff --git a/files/pt-pt/learn/css/howto/css_faq/index.html b/files/pt-pt/learn/css/howto/css_faq/index.html new file mode 100644 index 0000000000..357e271657 --- /dev/null +++ b/files/pt-pt/learn/css/howto/css_faq/index.html @@ -0,0 +1,229 @@ +--- +title: Perguntas Frequentes sobre CSS +slug: Learn/CSS/Howto/FAQ_de_CSS +tags: + - CSS + - Exemplo + - FAQ + - Guía + - Web + - questões +translation_of: Learn/CSS/Howto/CSS_FAQ +--- +

Why doesn't my CSS, which is valid, render correctly?

+ +

Browsers use the DOCTYPE declaration to choose whether to show the document using a mode that is more compatible  with Web standards or with old browser bugs. Using a correct and modern DOCTYPE declaration at the start of your HTML will improve browser standards compliance.

+ +

Modern browsers have two main rendering modes:

+ + + +

Gecko-based browsers, have a third Almost Standards Mode that has only a few minor quirks.

+ +

This is a list of the most commonly used DOCTYPE declarations that will trigger Standards or Almost Standards mode:

+ +
<!DOCTYPE html> /* This is the HTML5 doctype. Given that each modern browser uses an HTML5
+                   parser, this is the recommended doctype */
+
+<!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">
+
+ +

When at all possible, you should just use the HTML5 doctype.

+ +

Why doesn't my CSS, which is valid, render at all?

+ +

Here are some possible causes:

+ + + +

What is the difference between id and class?

+ +

HTML elements can have an id and/or class attribute. The id attribute assigns a name to the element it is applied to, and for valid markup, there can be only one element with that name. The class attribute assigns a class name to the element, and that name can be used on many elements within the page. CSS allows you to apply styles to particular id and/or class names.

+ + + +

It is generally recommended to use classes as much as possible, and to use ids only when absolutely necessary for specific uses (like to connect label and form elements or for styling elements that must be semantically unique):

+ + + +
+

Note: See Selectors for more information.

+
+ +

How do I restore the default value of a property?

+ +

Initially CSS didn't provide a "default" keyword and the only way to restore the default value of a property is to explicitly re-declare that property. For example:

+ +
/* Heading default color is black */
+h1 { color: red; }
+h1 { color: black; }
+ +

This has changed with CSS 2; the keyword initial is now a valid value for a CSS property. It resets it to its default value, which is defined in the CSS specification of the given property.

+ +
/* Heading default color is black */
+h1 { color: red; }
+h1 { color: initial; }
+ +

How do I derive one style from another?

+ +

CSS does not exactly allow one style to be defined in terms of another. (See Eric Meyer's note about the Working Group's stance). However, assigning multiple classes to a single element can provide the same effect, and CSS Variables now provide a way to define style information in one place that can be reused in multiple places.

+ +

How do I assign multiple classes to an element?

+ +

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.

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

If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

+ +

Why don't my style rules work properly?

+ +

Style rules that are syntactically correct may not apply in certain situations. You can use DOM Inspector's CSS Style Rules view to debug problems of this kind, but the most frequent instances of ignored style rules are listed below.

+ +

HTML elements hierarchy

+ +

The way CSS styles are applied to HTML elements depends also on the elements hierarchy. It is important to remember that a rule applied to a descendent overrides the style of the parent, in spite of any specificity or priority of CSS rules.

+ +
.news { color: black; }
+.corpName { font-weight: bold; color: red; }
+
+<!-- news item text is black, but corporate name is red and in bold -->
+<div class="news">
+   (Reuters) <span class="corpName">General Electric</span> (GE.NYS) announced on Thursday...
+</div>
+
+ +

In case of complex HTML hierarchies, if a rule seems to be ignored, check if the element is inside another element with a different style.

+ +

Explicitly re-defined style rule

+ +

In CSS stylesheets, order is important. If you define a rule and then you re-define the same rule, the last definition is used.

+ +
#stockTicker { font-weight: bold; }
+.stockSymbol { color: red; }
+/*  other rules             */
+/*  other rules             */
+/*  other rules             */
+.stockSymbol { font-weight: normal; }
+
+<!-- most text is in bold, except "GE", which is red and not bold -->
+<div id="stockTicker">
+   NYS: <span class="stockSymbol">GE</span> +1.0 ...
+</div>
+
+ +

To avoid this kind of error, try to define rules only once for a certain selector, and group all rules belonging to that selector.

+ +

Use of a shorthand property

+ +

Using shorthand properties for defining style rules is good because it uses a very compact syntax. Using shorthand with only some attributes is possible and correct, but it must be remembered that undeclared attributes are automatically reset to their default values. This means that a previous rule for a single attribute could be implicitly overridden.

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

In the previous example the problem occurred on rules belonging to different elements, but it could happen also for the same element, because rule order is important.

+ +
#stockTicker {
+   font-weight: bold;
+   font: 12px Verdana;  /* font-weight is now set to normal */
+}
+
+ +

Use of the * selector

+ +

The * wildcard selector refers to any element, and it has to be used with particular care.

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

In this example the body * selector applies the rule to all elements inside body, at any hierarchy level, including the .stockUp class. So font-weight: bold; applied to the .corpName class is overridden by font-weight: normal; applied to all elements in the body.

+ +

The use of the * selector should be minimized as it is a slow selector, especially when not used as the first element of a selector. Its use should be avoided as much as possible.

+ +

Specificity in CSS

+ +

When multiple rules apply to a certain element, the rule chosen depends on its style specificity. Inline style (in HTML style attributes) has the highest specificity and will override any selectors, followed by ID selectors, then class selectors, and eventually element selectors. The text color of the below {{htmlelement("div")}} will therefore be red.

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

The rules are more complicated when the selector has multiple parts. More detailed information about how selector specificity is calculated can be found in the CSS 2.1 Specification chapter 6.4.3.

+ +

What do the -moz-*, -ms-*, -webkit-*, -o-* and -khtml-* properties do?

+ +

These properties, called prefixed properties, are extensions to the CSS standard. They allow use of experimental and non-standard features in browsers without polluting the regular namespace, preventing future incompatibilities to arise when the standard is extended.

+ +

The use of such properties on production websites is not recommended — they have already created a huge web compatibility mess. For example, many developers only using the -webkit- prefixed version of a property when the non-prefixed version is supported across all browsers meant that a feature relying on that property would break in non-webkit-based browsers, completely needlessly. This problem got so bad that other browsers started to implement -webkit- prefixed aliases to improve web compatibility, as specified in the Compatibility Living Standard.

+ +

In fact most browsers now do not use CSS prefixes when implementing experimental features, insteading implementing those features only on Nightly browser versions or similar.

+ +

If you need to use prefixes in your work, you are advised to write your code in a way that uses the prefixed versions first, but then includes a non-prefixed standard version afterwards so it can automatically override the prefixed versions where supported. For example:

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

Note: For more information on dealing with prefixed properties, see Handling common HTML and CSS problems — Handling CSS prefixes from our Cross-browser testing module.

+
+ +
+

Note: See the Mozilla CSS Extensions page for more information on the Mozilla-prefixed CSS properties.

+
+ +

How does z-index relate to positioning?

+ +

The z-index property specifies the stack order of elements.

+ +

An element with a higher z-index/stack order is always rendered in front of an element with a lower z-index/stack order on the screen. Z-index will only work on elements that have a specified position (position:absolute, position:relative, or position:fixed).

+ +
+

Nota: For more information, see our Positioning learning article, and in particular the Introducing z-index section.

+
diff --git a/files/pt-pt/learn/css/howto/faq_de_css/index.html b/files/pt-pt/learn/css/howto/faq_de_css/index.html deleted file mode 100644 index 357e271657..0000000000 --- a/files/pt-pt/learn/css/howto/faq_de_css/index.html +++ /dev/null @@ -1,229 +0,0 @@ ---- -title: Perguntas Frequentes sobre CSS -slug: Learn/CSS/Howto/FAQ_de_CSS -tags: - - CSS - - Exemplo - - FAQ - - Guía - - Web - - questões -translation_of: Learn/CSS/Howto/CSS_FAQ ---- -

Why doesn't my CSS, which is valid, render correctly?

- -

Browsers use the DOCTYPE declaration to choose whether to show the document using a mode that is more compatible  with Web standards or with old browser bugs. Using a correct and modern DOCTYPE declaration at the start of your HTML will improve browser standards compliance.

- -

Modern browsers have two main rendering modes:

- - - -

Gecko-based browsers, have a third Almost Standards Mode that has only a few minor quirks.

- -

This is a list of the most commonly used DOCTYPE declarations that will trigger Standards or Almost Standards mode:

- -
<!DOCTYPE html> /* This is the HTML5 doctype. Given that each modern browser uses an HTML5
-                   parser, this is the recommended doctype */
-
-<!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">
-
- -

When at all possible, you should just use the HTML5 doctype.

- -

Why doesn't my CSS, which is valid, render at all?

- -

Here are some possible causes:

- - - -

What is the difference between id and class?

- -

HTML elements can have an id and/or class attribute. The id attribute assigns a name to the element it is applied to, and for valid markup, there can be only one element with that name. The class attribute assigns a class name to the element, and that name can be used on many elements within the page. CSS allows you to apply styles to particular id and/or class names.

- - - -

It is generally recommended to use classes as much as possible, and to use ids only when absolutely necessary for specific uses (like to connect label and form elements or for styling elements that must be semantically unique):

- - - -
-

Note: See Selectors for more information.

-
- -

How do I restore the default value of a property?

- -

Initially CSS didn't provide a "default" keyword and the only way to restore the default value of a property is to explicitly re-declare that property. For example:

- -
/* Heading default color is black */
-h1 { color: red; }
-h1 { color: black; }
- -

This has changed with CSS 2; the keyword initial is now a valid value for a CSS property. It resets it to its default value, which is defined in the CSS specification of the given property.

- -
/* Heading default color is black */
-h1 { color: red; }
-h1 { color: initial; }
- -

How do I derive one style from another?

- -

CSS does not exactly allow one style to be defined in terms of another. (See Eric Meyer's note about the Working Group's stance). However, assigning multiple classes to a single element can provide the same effect, and CSS Variables now provide a way to define style information in one place that can be reused in multiple places.

- -

How do I assign multiple classes to an element?

- -

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.

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

If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

- -

Why don't my style rules work properly?

- -

Style rules that are syntactically correct may not apply in certain situations. You can use DOM Inspector's CSS Style Rules view to debug problems of this kind, but the most frequent instances of ignored style rules are listed below.

- -

HTML elements hierarchy

- -

The way CSS styles are applied to HTML elements depends also on the elements hierarchy. It is important to remember that a rule applied to a descendent overrides the style of the parent, in spite of any specificity or priority of CSS rules.

- -
.news { color: black; }
-.corpName { font-weight: bold; color: red; }
-
-<!-- news item text is black, but corporate name is red and in bold -->
-<div class="news">
-   (Reuters) <span class="corpName">General Electric</span> (GE.NYS) announced on Thursday...
-</div>
-
- -

In case of complex HTML hierarchies, if a rule seems to be ignored, check if the element is inside another element with a different style.

- -

Explicitly re-defined style rule

- -

In CSS stylesheets, order is important. If you define a rule and then you re-define the same rule, the last definition is used.

- -
#stockTicker { font-weight: bold; }
-.stockSymbol { color: red; }
-/*  other rules             */
-/*  other rules             */
-/*  other rules             */
-.stockSymbol { font-weight: normal; }
-
-<!-- most text is in bold, except "GE", which is red and not bold -->
-<div id="stockTicker">
-   NYS: <span class="stockSymbol">GE</span> +1.0 ...
-</div>
-
- -

To avoid this kind of error, try to define rules only once for a certain selector, and group all rules belonging to that selector.

- -

Use of a shorthand property

- -

Using shorthand properties for defining style rules is good because it uses a very compact syntax. Using shorthand with only some attributes is possible and correct, but it must be remembered that undeclared attributes are automatically reset to their default values. This means that a previous rule for a single attribute could be implicitly overridden.

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

In the previous example the problem occurred on rules belonging to different elements, but it could happen also for the same element, because rule order is important.

- -
#stockTicker {
-   font-weight: bold;
-   font: 12px Verdana;  /* font-weight is now set to normal */
-}
-
- -

Use of the * selector

- -

The * wildcard selector refers to any element, and it has to be used with particular care.

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

In this example the body * selector applies the rule to all elements inside body, at any hierarchy level, including the .stockUp class. So font-weight: bold; applied to the .corpName class is overridden by font-weight: normal; applied to all elements in the body.

- -

The use of the * selector should be minimized as it is a slow selector, especially when not used as the first element of a selector. Its use should be avoided as much as possible.

- -

Specificity in CSS

- -

When multiple rules apply to a certain element, the rule chosen depends on its style specificity. Inline style (in HTML style attributes) has the highest specificity and will override any selectors, followed by ID selectors, then class selectors, and eventually element selectors. The text color of the below {{htmlelement("div")}} will therefore be red.

- -
div { color: black; }
-#orange { color: orange; }
-.green { color: green; }
-
-<div id="orange" class="green" style="color: red;">This is red</div>
-
- -

The rules are more complicated when the selector has multiple parts. More detailed information about how selector specificity is calculated can be found in the CSS 2.1 Specification chapter 6.4.3.

- -

What do the -moz-*, -ms-*, -webkit-*, -o-* and -khtml-* properties do?

- -

These properties, called prefixed properties, are extensions to the CSS standard. They allow use of experimental and non-standard features in browsers without polluting the regular namespace, preventing future incompatibilities to arise when the standard is extended.

- -

The use of such properties on production websites is not recommended — they have already created a huge web compatibility mess. For example, many developers only using the -webkit- prefixed version of a property when the non-prefixed version is supported across all browsers meant that a feature relying on that property would break in non-webkit-based browsers, completely needlessly. This problem got so bad that other browsers started to implement -webkit- prefixed aliases to improve web compatibility, as specified in the Compatibility Living Standard.

- -

In fact most browsers now do not use CSS prefixes when implementing experimental features, insteading implementing those features only on Nightly browser versions or similar.

- -

If you need to use prefixes in your work, you are advised to write your code in a way that uses the prefixed versions first, but then includes a non-prefixed standard version afterwards so it can automatically override the prefixed versions where supported. For example:

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

Note: For more information on dealing with prefixed properties, see Handling common HTML and CSS problems — Handling CSS prefixes from our Cross-browser testing module.

-
- -
-

Note: See the Mozilla CSS Extensions page for more information on the Mozilla-prefixed CSS properties.

-
- -

How does z-index relate to positioning?

- -

The z-index property specifies the stack order of elements.

- -

An element with a higher z-index/stack order is always rendered in front of an element with a lower z-index/stack order on the screen. Z-index will only work on elements that have a specified position (position:absolute, position:relative, or position:fixed).

- -
-

Nota: For more information, see our Positioning learning article, and in particular the Introducing z-index section.

-
diff --git a/files/pt-pt/learn/css/howto/generated_content/index.html b/files/pt-pt/learn/css/howto/generated_content/index.html new file mode 100644 index 0000000000..523c408aad --- /dev/null +++ b/files/pt-pt/learn/css/howto/generated_content/index.html @@ -0,0 +1,188 @@ +--- +title: Conteúdo +slug: Web/CSS/Como_começar/Conteúdo +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Howto/Generated_content +--- +

{{ PreviousNext("CSS:Como começar:Cor", "CSS:Como começar:Listas") }}

+ +

Esta página descreve algumas maneiras que você pode usar no CSS para adicionar conteúdo quando um documento é exibido.

+ +

Você modifica sua folha de estilo para adicionar conteúdo de texto e uma imagem.

+ +

Informação: Conteúdo

+ +

Uma das vantagens importantes das CSS é que ele o ajuda a separar o estilo do documento do seu conteúdo. Mas há situações onde faz sentido especificar certo conteúdo como parte de sua folha de estilo, não como parte do seu documento.

+ +

O conteúdo especificado em uma folha de estilo pode consistir em texto ou imagens. Você especifica o conteúdo em sua folha de estilo quando o conteúdo tem uma ligação próxima à estrutura do documento.

+ + + + + + + + +
Mais detalhes
Especificar o conteúdo em uma folha de estilo pode causar complicações. Por exemplo, você pode ter versões diferentes da língua do seu documento que compartilham uma folha de estilo. Se parte da folha de estilo tem que ser traduzida, isto mostra que você precisa por estas partes da folha de estilo em arquivos separados e arrumá-los para então ligá-los com a versão apropriada da língua do seu documento. +

Estas complicações não surgem se o conteúdo que você especificou consistir em símbolos ou imagens que se aplicam em todas as línguas e culturas.

+ +


+ O conteúdo especificado em uma folha de estilo não se tornará parte do DOM.

+
+ +

Conteúdo do texto

+ +

CSS pode inserir um texto antes ou depois de um elemento. Para especificar isto, faça uma regra e adicione :before ou :after ao seletor. Na declaração, especifique a propriedade content com o conteúdo do texto como seu valor.

+ + + + + + + + +
Exemplo
Esta regra adiciona o texto Referência: antes de todo elemento com a classe ref: +
+
+.ref:before {
+  font-weight: bold;
+  color: navy;
+  content: "Referência: ";
+  }
+
+
+
+ + + + + + + + +
Mais detalhes
O caractere de configuração de uma folha de estilo é por padrão o UTF-8, mas isto pode ser especificado na ligação, na própria folha de estilo ou por outras maneiras. Para detalhes, veja 4.4 CSS style sheet representation na CSS Specification. +

Caracteres individuais podem às vezes ser especificados por um mecanismo de escape que use o contra barra (\) com o caráter de escape. Por exemplo, \265B é um símbolo do xadrez para a rainha preta ♛. Para detalhes, veja Referring to characters not represented in a character encoding e também Characters and case em CSS Specification.

+
+ +

Conteúdo da imagem

+ +

Para adicionar uma imagem antes ou depois de um elemento, você pode especificar a URL de um arquivo de imagem no valor da propriedade content.

+ + + + + + + + +
Exemplo
Esta regra adiciona um espaço e um ícone depois de cada ligação da classe glossary: +
+
+a.glossary:after {content: " " url("../images/glossary-icon.gif");}
+
+
+
+ +


+ Para adicionar uma imagem ao fundo de um elemento, especifique a URL de um arquivo de imagem no valor da propriedade background. Isto é uma propriedade que especifica a cor do fundo, a imagem, como a imagem repete, e alguns outros detalhes.

+ + + + + + + + +
Exemplo
Esta regra configura o fundo de um elemento específico, usando uma URL para especificar um arquivo de imagem. +

O seletor especifica o id do elemento. O valor no-repeat faz a imagem aparecer apenas uma vez:

+ +
+
+#sidebar-box {background: url("../images/sidebar-ground.png") no-repeat;}
+
+
+
+ + + + + + + + +
Mais detalhes
Para informações sobre propriedades individuais que afetam o fundo, e sobre outras opções que você pode especificar para as imagens de fundo, veja The background na CSS Specification.
+ +

Ação: Adicionando uma imagem de fundo

+ +

Esta imagem é um quadrado branco com uma linha azul em baixo. Baixe o arquivo desta imagem no mesmo diretório do seu arquivo CSS:

+ + + + + + + +
Image:Blue-rule.png
+ +

(Por exemplo, clique com o botão direito sobre isto para abrir o menu de contexto, então escolha Salvar Imagem Como... e especifique o diretório que você está usando para este tutorial.)

+ +

Edite o seu arquivo CSS e adicione esta regra ao corpo, configurando a imagem de fundo para a página inteira.

+ +
+
background: url("Blue-rule.png");
+
+
+ +

O valor repeat é o padrão, então isto não precisa ser especificado. A imagem é repetida horizontal e verticalmente, dando a aparência parecida com a de um papel de escrita com linhas:

+ +
+

Image:Blue-rule-ground.png

+ +
+
+

Cascading Style Sheets

+
+ +
+

Cascading Style Sheets

+
+
+
+ + + + + + + + +
Desafio
Baixe esta imagem: + + + + + + +
Image:Yellow-pin.png
+ +

Adicione uma regra à sua folha de estilo então isto mostrará a imagem no começo de cada linha:

+ +
+

Image:Blue-rule-ground.png

+ +
+
image:Yellow-pin.png Cascading Style Sheets
+ +
image:Yellow-pin.png Cascading Style Sheets
+
+
+
+ +

O que vem depois?

+ +

Uma maneira comum de adicionar conteúdo à folha de estilo é marcar os itens em listas. Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

+ +

A próxima página descreve como especificar o estilo para elementos de listas: Listas

+ +

{{ PreviousNext("CSS:Como começar:Cor", "CSS:Como começar:Listas") }}

diff --git a/files/pt-pt/learn/css/styling_text/fundamentals/index.html b/files/pt-pt/learn/css/styling_text/fundamentals/index.html new file mode 100644 index 0000000000..373688d00f --- /dev/null +++ b/files/pt-pt/learn/css/styling_text/fundamentals/index.html @@ -0,0 +1,158 @@ +--- +title: Estilos de texto +slug: Web/CSS/Como_começar/Estilos_de_texto +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Styling_text/Fundamentals +translation_of_original: Web/Guide/CSS/Getting_started/Text_styles +--- +

{{ PreviousNext("CSS:Como começar:CSS legível", "CSS:Como começar:Cor") }}

+ +

Esta página dá mais exemplos de estilos de texto.

+ +

Você modifica sua folha de estilo de amostra para usar diferentes fontes.

+ +

Informação: Estilos de texto

+ +

CSS tem várias propriedades para estilos de texto.

+ +

Há uma conveniente propriedade de abreviação de caracteres/palavras que facilitam a escrita, font, que você pode usar para especificar várias coisas de uma vez — por exemplo:

+ + + + + + + + + + +
Exemplo
+
+
+p {font: italic 75%/125% "Comic Sans MS", cursive;}
+
+
+ +

Esta regra coloca várias propriedades da fonte, fazendo todos os parágrafos em itálico.

+ +

O tamanho da fonte é três quartos (75%) do tamanho em cada elemento do paragrafo principal e a altura da linha é 125% (um pouco mais espaçada que o normal).

+ +

O tipo da fonte é Comic Sans MS, mas se a fonte não estiver disponível então o navegador usará sua fonte cursiva padrão (escrita a mão).

+ +

A regra tem o efeito colateral de desativar o negrito e as letras minúsculas (colocando-os no estilo normal)

+
+ +

Tipos de fonte

+ +

Você não pode predizer quais fontes os leitores do seu documento terão. Então quando você especifica tipos de fonte é uma boa idéia colocar uma lista de alternativas em ordem de preferência.

+ +

Acabe a lista com um dos tipos de fontes internas padrão: serif, sans-serif, cursive, fantasy ou monospace. (Algumas destas podem ser configuradas nas Opções do seu navegador.)

+ +

Se o tipo não for suportado por algumas características no documento, então o navegador pode substituí-lo por um tipo diferente. Por exemplo, o documento pode conter caracteres especiais que a fonte não suporte. Se o navegador puder encontrar outra fonte que tenha os caracteres, então ele usará a outra fonte.

+ +

Para especificar um tipo de fonte por conta própria, use a propriedade font-family.

+ +

Tamanho da fonte

+ +

Leitores que usam os navegadores Mozilla podem configurar o tamanho padrão das fontes em Opções, e mudar o tamanho do texto quando lêem uma página, isso a torna boa para você usá-la com tamanho relativos onde você puder.

+ +

Você pode usar alguns valores internos para o tamanho das fontes, como: small, medium e large. Você pode também usar valores relativos para o tamanho das fontes do elemento primário, como: smaller, larger, 150% ou 1.5em.

+ +

Se necessário você pode especificar um tamanho atual, como: 12px (12 pixels) para um instrumento de exibição ou 12pt (12 pontos) para uma impressora. Este tamanho é nominalmente a largura de uma letra m, mas fontes variam na maneira do tamanho, você vê relatos do tamanho que você especifica.

+ +

Para especificar um tamanho de fonte por conta própria, use a propriedade font-size.

+ +

Altura da linha

+ +

A altura da linha especifica o espaçamento entre linhas. Se seu documento tem longos parágrafos com muitas linhas, um espaçamento mais largo que o normal faz com que a leitura seja mais fácil, especialmente se o tamanho da fonte for pequeno.

+ +

Para especificar a altura da linha por conta própria, use a propriedade line-height.

+ +

Decoração

+ +

A propriedade separada text-decoration pode especificar outros estilos, como underline ou line-through. Você pode configurar isto para none removendo explicitamente qualquer decoração.

+ +

Outras propriedades

+ +

Para especificar itálico por conta própria, use font-style: italic;
+ Para especificar negrito por conta própria, use font-weight: bold;
+ Para especificar letras minúsculas por conta própria, use font-variant: small-caps;

+ +

Para tornar qualquer destes valores individualmente desativado, você pode especificar o valor normal ou inherit.

+ + + + + + + + +
Mais detalhes
Você pode especificar os estilos do texto em uma variedade de outras maneiras. +

Por exemplo, algumas propriedades mencionadas aqui têm outros valores que podem ser usados.

+ +

Em uma folha de estilo complexa, evite usar a propriedade de abreviação de caracteres/palavras que facilitam a escrita font, por causa de seus efeitos colaterais (o re-escolher de outras propriedades individuais).

+ +

Para maiores detalhes sobre as propriedades relacionadas às fontes, veja Fonts na especificação do CSS. Para maiores detalhes sobre decoração de textos, veja Text.

+
+ +

Ação: Especificando fontes

+ +

Para um documento de amostra, você pode escolher a fonte do elemento BODY e o resto do documento herda as configurações.

+ +

Edite seu arquivo CSS. Adicione esta regra para mudar a fonte completamente. O topo do arquivo CSS é um local lógico para isto, mas isto terá o mesmo efeito em qualquer lugar que for posicionado:

+ +
+
body {font: 16px "Comic Sans MS", cursive;}
+
+
+ +

Adicione um comentário à regra, e deixe um espaço em branco para fazer sua disposição preferido.

+ +

Atualize seu navegador para ver o efeito. Se o seu sistema tem Comic Sans MS, ou outra fonte cursiva que não suporta itálico, então seu navegador escolhe um tipo diferente de fonte para o texto em itálico na primeira linha:

+ + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ +

Da barra de menu do seu navegador, escolha Exibir – Tamanho do Texto – Aumentar. Mesmo que o estilo especificado seja 16 pixels, um usuário lendo o documento pode mudar o tamanho.

+ + + + + + + + +
Desafio
Sem mudar mais nada, faça todas as seis letras iniciais duas vezes o tamanho na fonte serifada padrão do navegador: + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+
+ +

O que vem depois?

+ +

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

+ +

Seu documento de amostra está pronto para usar várias cores nomeadas. A próxima página lista os nomes das cores padrão e explica como você pode especificar outras: Cor

+ +

{{ PreviousNext("CSS:Como começar:CSS legível", "CSS:Como começar:Cor") }}

diff --git a/files/pt-pt/learn/css/styling_text/index.html b/files/pt-pt/learn/css/styling_text/index.html new file mode 100644 index 0000000000..5d00bc90c5 --- /dev/null +++ b/files/pt-pt/learn/css/styling_text/index.html @@ -0,0 +1,136 @@ +--- +title: Estilizar texto +slug: Learn/CSS/Estilo_de_texto +tags: + - CSS + - Hiperligações + - Principiante + - Texto + - Tipos de Letra + - letra + - lina + - listas + - modulo + - sombra + - tipo de letra + - tipos de letra da Web +translation_of: Learn/CSS/Styling_text +--- +
{{LearnSidebar}}
+ +

Com os conceitos básicos da linguagem CSS cobertos, o próximo tópico de CSS para se concentrar será o estilo de texto - uma das coisas mais comuns que irá fazer com CSS. Aqui, nós vamos ver os fundamentos do estilo de texto, incluindo a configuração do tipo de letra, negrito, itálico, espaçamento de linha e letra, sombras e outros recursos de texto. Nós completamos o módulo ao analisar a aplicação de tipos de letra personalizadas para a sua página, e listas de estilo e hiperligações.

+ +

Pré-requisitos

+ +

Before starting this module, you should already have basic familiarity with HTML, as discussed in the Introduction to HTML module, and be comfortable with CSS fundamentals, as discussed in Introduction to CSS.

+ +
+

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin, CodePen or Thimble.

+
+ +

Guias

+ +

This module contains the following articles, which will teach you all of the essentials behind styling HTML text content.

+ +
+
Fundamental text and font styling
+
In this article we go through all the basics of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.
+
Styling lists
+
Lists behave like any other text for the most part, but there are some CSS properties specific to lists that you need to know about, and some best practices to consider. This article explains all.
+
Styling links
+
When styling links, it is important to understand how to make use of pseudo-classes to style link states effectively, and how to style links for use in common varied interface features such as navigation menus and tabs. We'll look at all these topics in this article.
+
Web fonts
+
Here we will explore web fonts in detail — these allow you to download custom fonts along with your web page, to allow for more varied, custom text styling.
+
+ +

Avaliações

+ +

The following assessments will test your understanding of the text styling techniques covered in the guides above.

+ +
+
Typesetting a community school homepage
+
In this assessment we'll test your understanding of styling text by getting you to style the text for a community school's homepage.
+
+ +
+ + + + + +
diff --git a/files/pt-pt/learn/css/styling_text/styling_lists/index.html b/files/pt-pt/learn/css/styling_text/styling_lists/index.html new file mode 100644 index 0000000000..cff2108b51 --- /dev/null +++ b/files/pt-pt/learn/css/styling_text/styling_lists/index.html @@ -0,0 +1,362 @@ +--- +title: Listas +slug: Web/CSS/Como_começar/Listas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Styling_text/Styling_lists +translation_of_original: Web/Guide/CSS/Getting_started/Lists +--- +

{{ PreviousNext("CSS:Como começar:Conteúdo", "CSS:Como começar:Caixas") }}

+ +

Esta página descreve como você pode usar as CSS para especificar a aparência das listas.

+ +

Você cria um novo documento de amostra contendo listas, e uma nova folha de estilo que estiliza as listas.

+ +

Informação: Listas

+ +

Se você resolveu o desafio da última página (Conteúdo), então você viu como você pode adicionar conteúdo antes de qualquer elemento para mostrar isto como o item de uma lista.

+ +

CSS proporciona propriedades especiais que foram designadas para listas. Geralmente é mais conveniente usar estas propriedades sempre que você puder.

+ +

Para especificar o estilo para uma lista, use a propriedade list-style para especificar o tipo de marcador.

+ +

O seletor nas regras do seu CSS pode selecionar qualquer um dos elementos na sua lista de itens (por exemplo, LI), ou isto pode selecionar o elemento primário da lista (por exemplo, UL). Então os elementos da lista herdam o estilo.

+ +

Listas não ordenadas

+ +

Em uma lista não ordenada, cada item da lista é marcado da mesma maneira.

+ +

CSS tem três tipos de marcador. Aqui está como seu navegador os mostra:

+ + + +

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

+ + + + + + + + +
Exemplo
Estas regras especificam diferentes marcadores para diferentes classes de itens da lista: +
+
+li.open {list-style: circle;}
+li.closed {list-style: disc;}
+
+
+ +

Quando estas classes são usadas em uma lista, elas distinguem entre os itens aberto (open) e fechado (closed):

+ +
+
+<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 será parecido com:

+ + + + + + + +
+
    +
  • Lorem ipsum
  • +
  • Dolor sit
  • +
  • Amet consectetuer
  • +
  • Magna aliquam
  • +
  • Autem veleum
  • +
+
+
+ +

Listas ordenadas

+ +

Em uma lista ordenada, cada item da lista é marcado diferentemente para mostrar a posição em seqüência.

+ +

Use a propriedade list-style para especificar o tipo de marcador:

+ + + + + + + + + + +
Exemplo
Esta regra especifica os elementos OL com a classe info, os itens são identificados com letras maiúsculas. +
+
+ol.info {list-style: upper-latin;}
+
+
+ +

Os elementos LI na lista herdam este estilo:

+ + + + + + + +
+
    +
  • Lorem ipsum
  • +
  • Dolor sit
  • +
  • Amet consectetuer
  • +
  • Magna aliquam
  • +
  • Autem veleum
  • +
+
+
+ + + + + + + + +
Mais detalhes
A propriedade list-style é uma propriedade "abreviada". Em folhas de estilo complexas você pode preferir usar propriedades separadas para configurar valores separados. Para detalhes sobre estas propriedades separadas, e mais detalhes sobre como as CSS especificam listas, veja Lists na CSS Specification. +

Se você está usando a linguagem de marcação como o HTML que proporciona tags convecionais para listas não ordenadas (UL) e ordenadas (OL), então é bom praticar usando tags da maneira que foi explicado. Contudo, você pode usar as CSS para fazer UL mostrar ordenado e OL para mostrar não ordenado se você precisar.

+ +

Os navegadores diferem no modo como implementam os estilos das listas. Não espere que sua folha de estilo dê resultados idênticos em todos os navegadores.

+
+ +

Contadores

+ +
+

Note:  Alguns navegadores não suportam contadores.

+
+ +

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

+ +

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

+ +

Em alguns elementos antes da contagem começar, re-inicie o contador com a propriedade counter-reset e o nome do seu contador. O principal dos elementos que você estiver contando é um bom lugar para isto, mas você pode usar qualquer elemento que esteja antes da lista de itens.

+ +

Em cada elemento que o contador incrementar, use a propriedade counter-increment e o nome do seu contador.

+ +

Para mostrar seu contador, adicione :before ou :after ao seletor e use a propriedade content (como fez na página anterior, Conteúdo).

+ +

No valor da propriedade content, especifique counter() com o nome do seu contador. Opcionalmente especifique um tipo. Os tipos são como na seção passada em Listas ordenadas.

+ +

Normalmente o elemento que mostra o contador também incrementa isto.

+ + + + + + + + +
Exemplo
Esta regra inicializa um contador para cada elemento H3 com a classe numbered: +
+
+h3.numbered {counter-reset: mynum;}
+
+
+ +

Esta regra mostra e incrementa o contador para cada elemento P com a classe numbered:

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

O resultado se parece com isto:

+ + + + + + + +
Cabeçalho + +

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+
+ + + + + + + + +
Mais detalhes
Você não pode usar contadores a menos que você saiba que todos os que lêem o seu documento têm um navegador que os suporta. +

Se você puder usar contadores, eles tem a vantagem de que você pode estilizar os contadores separadamente da lista de itens. No exemplo anterior, os contadores estão em negrito mas a os itens da lista não.

+ +

Você pode também usar contadores em meios mais complexos — por exemplo, para numerar seções, cabeçalhos, sub-cabeçalhos e parágrafos em documentos formais. Para detalhes, veja Automatic counters and numbering em CSS Specification.

+
+ +

Ação: Listas denominadas

+ +

Crie um novo documento HTML, doc2.html. Copie e cole o conteúdo daqui, tendo certeza de que você rola o mouse para pegar tudo isto:

+ +
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<HTML>
+<HEAD>
+<TITLE>Documento de amostra 2</TITLE>
+<LINK rel="stylesheet" type="text/css" href="style2.css">
+</HEAD>
+<BODY>
+
+<H3 id="oceans">Os oceanos</H3>
+<UL>
+<LI>Ártico</LI>
+<LI>Atlântico</LI>
+<LI>Pacífico</LI>
+<LI>Índico</LI>
+<LI>Antártico</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:

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

Se a disposição e o comentário não estiver ao seu gosto, mude-os.

+ +

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

+ + + + + + + +
+

Os oceanos

+ +
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+ +

Parágrafos numerados

+ +

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+ + + + + + + + +
Desafios
Adicione uma regra à sua folha de estilo, para numerar os oceanos usando numerais Romanos de i até v: + + + + + + +
+

Os oceanos

+ +
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+
+ +


+ Se o seu navegador suporta contadores, mude sua folha de estilo para identificar o cabeçalho com letras maiúsculas em parênteses como isto:

+ + + + + + + +
+

(A) Os oceanos

+ +

. . .

+ +

(B) Parágrafos numerados

+ +

. . .

+
+
+ +

O que vem depois?

+ +

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

+ +

Quando seu navegador exibe seu documento de amostra, cria espaços ao redor dos elementos quando eles são exibidos na página.

+ +

A próxima página descreve como você pode usar as CSS para trabalhar com formas subjacentes de elementos: Caixas

+ +

{{ PreviousNext("CSS:Como começar:Conteúdo", "CSS:Como começar:Caixas") }}

diff --git a/files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html b/files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html new file mode 100644 index 0000000000..9b401915f7 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html @@ -0,0 +1,293 @@ +--- +title: CSS - Essencial +slug: Learn/Comecar_com_a_Web/CSS_basico +tags: + - Aprender + - Beginner + - CSS + - CodingScripting + - Estilo + - 'I10n:priority' + - Web +translation_of: Learn/Getting_started_with_the_web/CSS_basics +--- +
{{LearnSidebar}} +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web")}}
+
+ +
+

CSS (Folhas de Estilo em Cascata) é o código que se utiliza para estilizar a sua página da Web. CSS - Elementar guia-o através do que precisa para começar. Vamos responder a perguntas deste género: Como é que eu coloco o meu texto a preto ou vermelho? Como é que eu faço para que o meu conteúdo apareça neste lugar do ecrã? Como é que eu decoro a minha página da Web, com cores e imagens de fundo?

+
+ +

Então, o que realmente é o CSS?

+ +

Tal como o HTML, o CSS não é bem uma linguagem de programação; também não é uma linguagem de demarcação. É uma linguagem de folha de estilos. Isto significa que permite aplicar estilos seletivamente aos elementos nos documentos HTML. Por exemplo, para selecionar todos os elementos do parágrafo numa página HTML e transformar o texto dentro deles em vermelho, iria escrever este CSS:

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

Vamos tentar: copie e cole estas três linhas de CSS num novo ficheiro do editor de texto, depois grave com o nome style.css na diretoria styles.

+ +

Mas ainda é preciso aplicar este CSS ao seu documento HTML. Se não, os estilos CSS não vão afetar a forma como o seu navegador apresenta o documento HTML. (Se não tem seguido o nosso projeto, leia Lidar com ficheiros e HTML - Essencial para saber o que fazer primeiro)

+ +
    +
  1. Abra o seu ficheiro index.html e cole a linha seguinte no cabeçalho (isto é, entre as marcas <head> e </head>): + +
    <link href="styles/style.css" rel="stylesheet" type="text/css">
    +
  2. +
  3. Guarde o ficheiro index.html e aceda-lhe no seu navegador. Deverá ver algo deste género:
  4. +
+ +

A mozilla logo and some paragraphs. The paragraph text has been styled red by our css.O texto dos seus parágrafos ficou vermelho. Parabéns! Acabou de escrever com sucesso o seu primeiro CSS.

+ +

Anatomia de um conjunto de regras de CSS

+ +

Vejamos o CSS acima com um pouco mais de detalhe:

+ +

+ +

A esta estrutura dá-se o nome conjunto de regras (geralmente, "regra" para abreviar). Repare nos nomes de cada parte:

+ +
+
Seletor
+
Neste caso, é o nome do elemento HTML, no início do conjunto de regras. Seleciona o(s) elemento(s) a que vai ser aplicado o estilo (neste caso, todos os elementos p). Para dar estilo a outro elemento, muda-se o seletor.
+
Declaração
+
Trata-se de uma única regra, como  color: red;, que especifica as propriedades que se pretendem modificar no elemento.
+
Propriedades
+
São as formas como se pode estilizar o elemento HTML (Neste caso, color é uma propriedade dos elementos {{htmlelement("p")}}). Em CSS, pode escolher que propriedades pretende modificar na regra.
+
Valor da propriedade
+
À direita da propriedade, depois dos dois pontos (:), temos o valor da propriedade, que escolhe uma das possíveis aparências que a propriedade pode indicar (há muitos mais valores para color além de red).
+
+ +

Repare em outros aspetos importantes da sintaxe:

+ + + +

Para modificar múltiplas propriedades, basta separá-las com o ponto e vírgula, assim:

+ +
p {
+  color: red;
+  width: 500px;
+  border: 1px solid black;
+}
+ +

Selecionar múltiplos elementos

+ +

Também pode selecionar vários elementos e aplicar um conjunto de regras único para todos eles. Inclua múltiplos seletores separados por vírgulas. Por exemplo:

+ +
p, li, h1 {
+  color: red;
+}
+ +

Diferentes tipos de seletor

+ +

Há muitos tipos diferentes de seletor. Por cima, apenas olhámos para seletores de elementos, que selecionam todos os elementos de determinado tipo no documento HTML a que são aplicados. Mas podemos fazer seleções mais específicas. Em baixo, estão alguns dos tipos mais comuns de seletores:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome do seletorO que é que este selecionaExemplo
Seletor de elemento (também chamado seletor de etiqueta ou tipo)Todos os elementos HTML do tipo especificado.p
+ Seleciona todos os elementos <p>
Seletor de ID O elemento da página com o ID especificado (numa página HTML, só pode haver um elemento para cada ID e vice-versa).#my-id
+ Seleciona <p id="my-id"> ou <a id="my-id"> (não devem existir ambos na mesma página)
Seletor de classeSeleciona o(s) elementos(s) da página com a classe especificada (é possível haver elementos diferentes com a mesma classe)..my-class
+ Seleciona <p class="my-class"> e também <a class="my-class">
Seletor de atributoSeleciona o(s) elementos(s) que tenham o atributo dado.img[src]
+ Seleciona <img src="myimage.png"> mas não seleciona <img>
Seletor de Pseudo-classeO(s) elemento(s) especificado(s), mas só quando estiverem no estado indicado. Ex: quando se tem cursor do rato sobre eles.a:hover
+ Seleciona <a>, mas só quando o cursor está sobre o link.
+ +

Existem muitos mais seletores para explorar, e pode encontrar uma lista mais detalhada no nosso Guia de seletores.

+ +

Fonte e texto

+ +

Agora que explorámos as bases do CSS, vamos acrescentar regras e informação ao nosso ficheiro style.css para que o exemplo tenha boa apresentação.

+ +
    +
  1. Primeiro, volte atrás e encontre o output de Google Fonts que guardou num lugar seguro. Acrescente o elemento {{htmlelement("link")}} no cabeçalho do index.html (entre etiquetas <head> e </head>). + +
    <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    +
  2. +
  3. De seguida, apague a regra que tinha no ficheiro style.css. Foi um bom teste, mas a cor vermelha não ficou muito bem.
  4. +
  5. Insira as linhas que se seguem, substituindo a linha de substituição pela linha font-family que obteve no site Google Fonts. (font-family indica o nome do tipo de letra). Esta regra estabelece um tamanho e tipo de letra global, em toda a página, já que o elemento <html> é o elemento raiz e todos os elementos aninhados herdam font-size e font-family: +
    html {
    +  font-size: 10px; /* px significa 'píxeis': o tamnho da letra base é duma altura de 10 píxeis */
    +  font-family: placeholder: aqui deve aparecero resto do output do Google fonts
    +}
    + +
    +

    Nota: num documento CSS, tudo o que esteja entre /* e */ é um comentário de CSS, que o navegador ignora quando processa o código. Os comentários servem para escrever notas úteis sobre o que está a fazer.

    +
    +
  6. +
  7. Agora estabelecemos o tamanho da letra para elementos textuais no corpo do HTML: ({{htmlelement("h1")}}, {{htmlelement("li")}}, e {{htmlelement("p")}}). Também vamos centrar o texto dos nossos títulos e especificar altura da linha de texto e espaçamento entre letras no corpo para o tornar mais legível: +
    h1 {
    +  font-size: 60px;
    +  text-align: center;
    +}
    +
    +p, li {
    +  font-size: 16px;
    +  line-height: 2;
    +  letter-spacing: 1px;
    +}
    +
  8. +
+ +

Pode ajustar os valores de px conforme achar que fica melhor, mas em geral, o design deve ter esta aparência:

+ +

a mozilla logo and some paragraphs. a sans-serif font has been set, the font sizes, line height and letter spacing are adjusted, and the main page heading has been centered

+ +

Caixas, caixas, é tudo sobre caixas

+ +

Quando escreve CSS, poderá notar que a maior parte do esforço é referente a caixas — configurar o seu tamanho, cor, posição, etc. Pode pensar na maioria dos elementos de HTML da sua página como caixas colocadas umas sobre a outras.

+ +

a big stack of boxes or crates sat on top of one another

+ +

Sem surpresa, a disposição de elementos em CSS assenta principalmente num modelo de caixa. Cada um dos blocos que ocupa espaço na sua página tem propriedades como:

+ + + +

three boxes sat inside one another. From outside to in they are labelled margin, border and padding

+ +

Nesta secção também vamos usar:

+ + + +

Portanto, vamos começar e acrescentar algum CSS à nossa página! Acrescente as novas regras no fim do ficheiro e não tenha medo de mudar os valores para ver como fica.

+ +

Alterar a cor da página

+ +
html {
+  background-color: #00539F;
+}
+ +

Esta regra estabelece uma cor de fundo na página inteira. Mude o código de cor para aquele que escolheu quando planeou o seu site.

+ +

Ordenar o corpo

+ +
body {
+  width: 600px;
+  margin: 0 auto;
+  background-color: #FF9500;
+  padding: 0 20px 20px 20px;
+  border: 5px solid black;
+}
+ +

Agora o elemento {{htmlelement("body")}}. Há várias declarações, então vamos ver uma de cada vez:

+ + + +

Posicionar e estilizar o título da nossa página principal

+ +
h1 {
+  margin: 0;
+  padding: 20px 0;
+  color: #00539F;
+  text-shadow: 3px 3px 1px black;
+}
+ +

Deve ter notado que há espaço em branco horrível no topo do conteúdo da página. Isto acontece porque o navegador aplica estilo por omissão ao elemento {{htmlelement("h1")}} (entre outros), mesmo que não se tenha aplicado qualquer CSS! Embora isso possa parecer má ideia, na prática até uma página sem folha de estilos tem que ter alguma legibilidade. Para nos livrarmos deste espaço, colocamos margin: 0;.

+ +

De seguida, colocámos o preenchimento por cima e por baixo a 20 píxeis, e demos ao texto a mesma cor que a cor de fundo do elemento {{htmlelement("html")}}.

+ +

Utilizámos uma propriedade interessante, text-shadow, que aplica sombreado ao texto de um elemento. Estes são os quatro valores da mesma:

+ + + +

Novamente, tente experimentar os valores para ver como fica!

+ +

Centrar a imagem

+ +
img {
+  display: block;
+  margin: 0 auto;
+}
+ +

Por fim, vamos centrar a imagem para ficar melhor. Utilizámos o truque de colocar margin: 0 auto como fizemos com o corpo, mas temos que fazer outra coisa. O elemento {{htmlelement("body")}} está ao nível de bloco, ou seja, ocupa toda a largura da página e podem ser-lhe aplicados valores de margem, e outros valores de espaçamento. Por outro lado, as imagens são elemento em linha, a que não se podem aplicar estes valores. Então, para a margem ser aplicada à imagem, temos que lhe atribuir comportamento ao nível do bloco com display: block;.

+ +
+

Nota: Estas instruções assumem que está a usar uma imagem mais pequena que a largura do corpo (600 píxeis). Se for maior, vai transbordar do corpo e ocupar espaço no resto da página. Para retificar isto, pode 1) reduzir a largura da imagem com um programa de edição gŕafica, ou 2) reduzir a imagem com CSS utilizando a propriedade {{cssxref("width")}} no elemento <img> com um valor mais pequeno, como 400 px;.

+
+ +
+

Nota: não se preocupe se ainda não entende display: block; e a distinção entre bloco e em linha (block-level/inline). Irá perceber à medida que estuda o CSS com mais profundidade. Pode descobrir mais sobre os diferentes valores de display na página de referência de display.

+
+ +

Conclusão

+ +

Se seguiu as instruções nesta página, a sua página deve ter este aspeto (e pode ver a nossa versão aqui):

+ +

a mozilla logo, centered, and a header and paragraphs. It now looks nicely styled, with a blue background for the whole page and orange background for the centered main content strip.

+ +

Se ficou preso, pode sempre comparar o seu trabalho com o exemplo terminado no GitHub.

+ +

Aqui, mal tocámos na superfície do CSS. Para saber mais, consulte o tópico de Aprender CSS.

+ +

{{PreviousMenuNext("Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web")}}

+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html b/files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html new file mode 100644 index 0000000000..6489964938 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html @@ -0,0 +1,119 @@ +--- +title: Lidar com ficheiros +slug: Learn/Comecar_com_a_Web/Lidar_com_ficheiros +tags: + - Beginner + - Ficheiros + - Guía + - HTML + - Programação Scripting + - 'l10n:priority' + - site da Web + - teoria +translation_of: Learn/Getting_started_with_the_web/Dealing_with_files +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web")}}
+ +
+

Um site da internet consiste em muitos ficheiros: conteúdo de texto, código, folhas de estilo, conteúdo de multimédia, e assim por diante. Enquanto estiver a criar o site, tem que reunir esses ficheiros numa estrutura conveniente no seu computador local, certificar-se que os mesmos podem comunicar uns com os outros e preparar a apresentação do seu conteúdo, antes de eventualmente enviar os ficheiros para um servidor. Este artigo, Lidar com ficheiros, apresenta algumas questões de que deverá estar ciente para poder configurar uma estrutura de ficheiros conveniente para o seu site.

+
+ +

Onde deve ficar o seu site no seu computador ?

+ +

Quando estiver a trabalhar num site localmente, no seu computador, deve manter todos os ficheiros relacionados numa única pasta que seja o reflexo da estrutura de ficheiros do site no servidor. Esta pasta pode ficar onde quiser, mas deve colocá-la num local de fácil acesso: talvez no seu Ambiente de Trabalho, a pasta do seu utilizador, ou a raiz do seu disco rígido.

+ +
    +
  1. Escolha um sítio para guardar os seus projetos relacionados com sites. Lá, crie uma pasta com o nome projetos-web (ou um nome semelhante). É aqui que vão morar todos os seus projetos de sites.
  2. +
  3. Dentro desta pasta, crie outra pasta para guardar o seu primeiro site. Pode-lhe chamar site-de-teste (ou algo mais criativo).
  4. +
+ +

Um aparte sobre nomes de pastas e ficheiros

+ +

Ao longo deste artigo poderá notar que os nomes que são dados às pastas e aos ficheiros estão todos em minúsculas e sem espaços. Isto porque:

+ +
    +
  1. Muitos computadores, particularmente servidores da internet, são sensíveis a maiúsculas. Por exemplo, se criar um ficheiro de imagem com o nome site-de-teste/MinhaImagem.jpg e depois noutro ficheiro tentar referir-se a ela com o nome site-de-teste/minhaimagem.jpg, pode não resultar.
  2. +
  3. Navegadores, servidores, e linguagens de programação não tratam os espaços da mesma forma. Por exemplo, se usar espaços no nome do ficheiro, alguns sistemas podem tratá-lo como dois nomes separados. Alguns servidores substituem os espaços por "%20" (código de carácter de espaços em URI), e assim arruínam os seus links.
  4. +
+ +

Por essas razões, é melhor habituar-se a escrever os nomes de pastas e ficheiros sem espaços e com palavras separadas por hífen, pelo menos até saber o que está a fazer. Desta forma, irá encontrar menos problemas mais tarde.

+ +

Inicialmente, é melhor separar palavras com hífen em vez de underscoremeu-ficheiro.html em vez de meu_ficheiro.html, pois o motor de pesquisa Google interpreta o hífen como separador de palavras, mas não o underscore.

+ +

Que estrutura deverá ter o seu site?

+ +

De seguida, vamos discutir a estrutura que deve ter o site de teste. As coisas mais comuns que temos em qualquer site são um ficheiro índice e pastas que organizam os ficheiros por tipo: imagens, folhas de estilo e scripts. Vamos criá-las agora:

+ +
    +
  1. index.html: Este ficheiro geralmente descreve o conteúdo da sua página principal, ou seja, o texto e imagens que as pessoas veem quando visitam o site pela primeira vez. Com um editor de texto, crie um ficheiro index.html e guarde-o dentro da pasta site-de-teste.
  2. +
  3. Pasta images: Esta pasta irá conter todas as imagens do seu site. Crie um pasta com este nome dentro da pasta site-de-teste.
  4. +
  5. Pasta styles: Esta pasta contém o código CSS que dá estilo ao conteúdo (por exemplo, cor do texto e do fundo). Crie-a dentro da pasta site-de-teste.
  6. +
  7. Pasta scripts: Esta pasta contém o código JavaScript que dá interatividade ao seu site (ex: botões que carregam dados quando premidos). Crie-adentro da pasta site-de-teste.
  8. +
+ +
+

Nota: Em computadores com Windows, pode ter dificuldade em ver nomes dos ficheiros, porque no Windows tem uma opção, ligada por omissão, para Esconder extensões de ficheiros conhecidas. Em geral, pode desligá-la no Explorador do Windows, selecionar Opções de pastas..., desmarcar a opção em questão, na caixa de seleção, e clicar OK. Para mais informações sobre a sua versão específica de Windows, faça uma pesquisa na internet. 

+
+ +

Caminhos de ficheiros

+ +

Para permitir a comunicação entre ficheiros, é necessário estabelecer os caminhos entre eles. Para demonstrar, vamos inserir algum HTML no ficheiro index.html que mostra a imagem que escolheu no artigo Qual será a aparência do meu site?

+ +
    +
  1. Copie a imagem escolhida para a pasta images.
  2. +
  3. Abra o ficheiro index.html, e copie o código exatamente como se mostra em baixo. Para já não se preocupe com o que significa — vamos olhar para estas estruturas mais tarde. +
    <!DOCTYPE html>
    +<html>
    +  <head>
    +    <meta charset="utf-8">
    +    <title>My test page</title>
    +  </head>
    +  <body>
    +    <img src="" alt="My test image">
    +  </body>
    +</html> 
    +
  4. +
  5. A linha <img src="" alt="My test image"> é o código HTML que insere uma imagem na página. É necessário dizer, neste trecho de código HTML, onde está a imagem. A mesma está dentro da diretoria images, a qual está na mesma diretoria que index.html. Para descer na estrutura de ficheiros, de index.html para a imagem, o caminho é images/nome-da-imagem. Por exemplo, se a mesma e chamasse firefox-icon.png, o caminho seria images/firefox-icon.png.
  6. +
  7. Insira este caminho no código HTML, entre as aspas neste trecho de código: src="".
  8. +
  9. Guarde o ficheiro HTML, depois carregue-o no seu navegador (com duplo clique). Deve conseguir ver o novo site, com a imagem! 
  10. +
+ +

A screenshot of our basic website showing just the firefox logo - a flaming fox wrapping the world

+ +

Algumas regras gerais sobre caminhos de ficheiros:

+ + + +

Por agora é tudo o que precisa de saber.

+ +
+

Nota: O Windows usa barras invertidas, como no caminho C:\windows. Mas em HTML, isso é irrelevante — mesmo que esteja a construir o site num sistema Windows, pode usar a barra normal, /.

+
+ +

Que mais deverá ser feito?

+ +

Por agora é tudo. A sua estrutura deverá ser como esta:

+ +

A file structure in mac os x finder, showing an images folder with an image in, empty scripts and styles folders, and an index.html file

+ +

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web")}}

+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html b/files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html new file mode 100644 index 0000000000..69fe6b79fa --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html @@ -0,0 +1,112 @@ +--- +title: Como funciona a Web +slug: Learn/Comecar_com_a_Web/Como_funciona_a_Web +tags: + - Aprender + - Beginner + - Cliente + - DNS + - HTTP + - IP + - Infraestrutura + - Servidor + - TCP + - 'l10n:priority' +translation_of: Learn/Getting_started_with_the_web/How_the_Web_works +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
+ +
+

Como a Web funciona, fornece uma visualização simplificada do que acontece quando visualiza uma página da Web num navegador da Web no seu computador ou dispositivo móvel.

+
+ +

Esta teoria não é essencial para escrever o código da Web em curto prazo, mas em pouco tempo, irá realmente começar a beneficiar da compreensão do que está a acontecer em segundo plano.

+ +

Servidores e clientes

+ +

Os computadores ligados à Web são chamados de clientes e servidores. Um diagrama simplificado de como eles interagem, parece-se como isto:

+ +

+ + + +

As outras partes da caixa de ferramentas

+ +

O cliente e o servidor que descrevemos acima não contam toda a história. Há muitas outras partes envolvidas, e iremos descrevê-las em baixo.

+ +

Por enquanto, vamos imaginar que a Web é uma estrada. Num extremo da estrada está o cliente, que é como a sua casa. Na outra extremidade da estrada está o servidor, que é uma loja na qual deseja comprar algo.

+ +

+ +

Além do cliente e do servidor, nós também precisamos cumprimentar:

+ + + +

Então, o que acontece exatamente?

+ +

Quando escreve um endereço web no seu browser (para a nossa analogia isso é como caminhar até à loja):

+ +
    +
  1. O navegador vai para o servidor DNS, e encontra o endereço real do servidor onde o sítio web vive (encontra o endereço da loja).
  2. +
  3. O navegador envia uma mensagem de pedido HTTP ao servidor, pedindo-lhe que envie uma cópia do website ao cliente (vai à loja e encomenda a sua mercadoria). Esta mensagem e todos os outros dados enviados entre o cliente e o servidor, é enviada através da sua ligação à Internet utilizando TCP/IP.
  4. +
  5. Desde que o servidor aprove o pedido do cliente, o servidor envia ao cliente uma mensagem "200 OK", o que significa "Claro que pode olhar para esse website! Aqui está", e depois começa a enviar os ficheiros do sítio web para o navegador como uma série de pequenos pedaços chamados packets / pacotes de dados (a loja dá-lhe os seus bens, e você trá-los de volta para a sua casa).
  6. +
  7. O navegador monta os pequenos pedaços num website completo e mostra-lho (os bens chegam à sua porta — coisas novas e brilhantes, espetacular!).
  8. +
+ +

DNS explicado

+ +

Os verdadeiros endereços web não são os nomes agradáveis e memoráveis que escreve na sua barra de endereços para encontrar os seus sítios web favoritos. São números especiais que têm este aspeto: 63.245.215.20.

+ +

Isto chama-se um {{Glossary("IP Address", "Endereço IP")}}, e representa uma localidade única na web. No entanto, não é muito fácil de lembrar, pois não? É por isso que foram inventados os Servidores de Nome de Domínio. Estes são servidores especiais que correspondem a um endereço web que digita no seu browser (como "mozilla.org") ao endereço real (IP) do website.

+ +

Os websites podem ser acedidos diretamente através dos seus endereços IP. Pode encontrar o endereço IP de um sítio web digitando o seu domínio numa ferramenta como o IP Checker.

+ +

A domain name is just another form of an IP address

+ +

Packets explicados

+ +

Anteriormente utilizámos o termo "packets" para descrever o formato em que os dados são enviados do servidor para o cliente. O que é que queremos dizer aqui? Basicamente, quando os dados são enviados através da web, são enviados como milhares de pequenos pedaços, para que muitos utilizadores da web possam descarregar o mesmo website ao mesmo tempo. Se os sítios web fossem enviados como um único grande pedaço, apenas um utilizador poderia descarregar um de cada vez, o que obviamente tornaria a web muito ineficiente e não muito divertida de utilizar.

+ +

Ver também

+ + + +

Créditos

+ +

Street photo: Street composing, por Kevin D.

+ +

{{PreviousMenu("Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}

+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html b/files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html new file mode 100644 index 0000000000..4601e08092 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html @@ -0,0 +1,237 @@ +--- +title: HTML - Essencial +slug: Learn/Comecar_com_a_Web/HTML_basicos +tags: + - Aprender + - CodingScripting + - HTML + - Principiante + - Web + - 'l10n:priority' +translation_of: Learn/Getting_started_with_the_web/HTML_basics +--- +
+
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web")}}
+ +
+

HTML (Linguagem de Marcação de Hipertexto) é o código que é utilizado para estruturar uma página da web e o seu conteúdo. Por exemplo, o conteúdo poderá ser estruturado dentro de um conjunto de parágrafos, uma lista de pontos com marcadores, ou utilizando imagens e tabelas de dados. Como o título sugere, este artigo irá dar-lhe uma compreensão básica do HTML e as suas funções.

+
+ +

Então, o que é realmente o HTML?

+ +

HTML não é uma linguagem de programação; é uma linguagem de marcação que define a estrutura do seu conteúdo. HTML consiste numa série de {{Glossary("element", "elementos")}}, que se utilizam para envolver, ou cercar, diferentes partes do conteúdo, e assim fazê-lo ter uma determinada aparência ou agir de determinada maneira. As {{Glossary("tag", "etiquetas")}} envolventes podem interligar as palavras ou imagens para outro lugar, colocar palavras em itálico, tornar a letra maior ou menor, e assim por diante. Por exemplo, veja a seguinte linha de conteúdo:

+ +
O meu gato é muito rabugento
+ +

Caso queiramos que a linha esteja separada de outras, podemos especificar que é um parágrafo envolvendo-a em etiquetas de parágrafo:

+ +
<p>O meu gato é muito rabugento</p>
+ +

Anatomia de um elemento HTML

+ +

Vamos explorar este elemento de parágrafo um pouco mais.

+ +

+ +

As partes principais do nosso elemento são:

+ +
    +
  1. A etiqueta de abertura: Consiste no nome do elemento (neste caso, p), envolto em parênteses angulares. Isto afirma onde começa o elemento, ou onde começa a ter efeito — neste caso, onde começa o parágrafo.
  2. +
  3. A etiqueta de fecho: É igual à de abertura, mas tem uma barra antes do nome do elemento. Isto afirma onde acaba o elemento — neste caso, onde fica o fim do parágrafo. Omitir a etiqueta de fecho é um erro de principiante comum e pode levar a resultados estranhos.
  4. +
  5. O conteúdo: É o conteúdo do elemento, que neste caso é só texto.
  6. +
  7. O elemento: A etiqueta de abertura, mais a etiqueta de fecho, mais o conteúdo, é igual ao elemento.
  8. +
+ +

Elementos também podem ter atributos, que se parecem assim:

+ +

+ +

Atributos contêm informação extra sobre o elemento que não quer que apareça no conteúdo. Aqui, class é o nome do atributo, e editor-note é o valor do atributo. O atributo class permite identificar o elemento como sendo parte de um grupo, que pode ser alvo de regras CSS e outras coisas.

+ +

Um atributo deverá ter sempre:

+ +
    +
  1. Um espaço entre si o nome do elemento (ou do atributo anterior, se esse elemento já possuir um ou mais atributos).
  2. +
  3. O nome do atributo, seguido de um sinal de igual.
  4. +
  5. O valor do atributo, envolto em abre e fecha aspas.
  6. +
+ +
+

Nota: Valores de atributos que não possuam espaço em branco ASCII (ou nenhum dos caracteres " ' = < >), mas recomendado que todos os valores de atributos sejam envoltos em aspas, para tornar o código mais consistente e compreensível.

+
+ +

Aninhar elementos

+ +

Também pode colocar elementos dentro de outros elementos  — chama-se a isto aninhar. Se quisermos declarar que o nosso gato é muito rabugento, podemos cercar a palavra "muito" com um elemento {{htmlelement("strong")}}, que significa que a palavra tem ênfase forte:

+ +
<p>O meu gato é <strong>muito</strong> rabugento.</p>
+ +

No entanto, tem que se certificar que os seus elementos estão devidamente aninhados: no exemplo em cima, abrimos o elemento {{htmlelement("p")}} primeiro, e depois o elemento {{htmlelement("strong")}} , portanto temos que fechar o elemento {{htmlelement("strong")}} primeiro, e só depois o {{htmlelement("p")}}. A linha seguinte está errada:

+ +
<p>O meu gato é <strong>muito rabugento.</p></strong>
+ +

Os elementos têm que abrir e fechar corretamente para que seja claro se estão dentro ou fora uns dos outros. Se ficarem sobrepostos como se mostrou em cima, o seu navegador vai tentar adivinhar o que quis dizer, e pode obter resultados inesperados. Então, não faça isso!

+ +

Elementos vazios

+ +

Alguns elementos não têm conteúdo, aos quais chamamos elementos vazios. Veja o elemento {{htmlelement("img")}} que já temos no nosso HTML:

+ +
<img src="images/firefox-icon.png" alt="My test image">
+ +

O mesmo contém dois atributos, mas não há etiqueta de fecho, </img>, nem conteúdo no seu interior, uma vez que um elemento de imagem não envolve conteúdo para o afetar. O seu propósito é incorporar uma imagem na página HTML, no local onde aparece.

+ +

Anatomia de um documento HTML

+ +

Assim terminamos as bases de elementos HTML individuais, mas eles não são muito úteis sozinhos. Vamos agora ver como os elementos se combinam para formar uma página HTML inteira. Voltemos ao código que escrevemos no ficheiro de exemplo index.html (que conhecemos no artigo Lidar com ficheiros):

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My test page</title>
+  </head>
+  <body>
+    <img src="images/firefox-icon.png" alt="My test image">
+  </body>
+</html>
+ +

Aqui temos:

+
+ + + +

Imagens

+ +

Vamos virar a nossa atenção para o elemento {{htmlelement("img")}} outra vez:

+ +
<img src="images/firefox-icon.png" alt="My test image">
+ +

Como já referimos, incorpora uma imagem na nossa página, no local onde aparece. Para tal recorre ao atributo src (source — fonte, origem), que contém o caminho para o ficheiro de imagem.

+ +

Também incluímos o atributo alt (alternativa). Neste atributo, você especifica texto descritivo para utilizadores que não conseguem ver a imagem, possivelmente porque:

+ +
    +
  1. Têm deficiências visuais. Utilizadores com deficiências visuais significativas costumam utilizar ferramentas chamadas leitores de ecrã que lhes lê o texto alternativo.
  2. +
  3. Alguma coisa correu mal e fez com que a imagem não fosse mostrada. Por exemplo, tente mudar deliberadamente o caminho no atributo src para torná-lo incorreto. Se guardar e recarregar a página, deve ver algo como isto em vez da imagem:
  4. +
+ +

+ +

As palavras-chave sobre texto alternativo são: "texto descritivo". Ou seja, deve dar ao leitor informação suficiente para ter uma boa ideia do que a imagem transmite. Neste exemplo, o texto atual, "My test image" não é nada bom. Uma alternativa muito melhor para o nosso logótipo do Firefox seria "Logótipo do Firefox: uma raposa flamejante a rodear o mundo."

+ +

Agora, tenta encontrar texto alternativo melhor para a tua imagem.

+ +
+

Nota: saiba mais sobre acessibilidade em MDN - Página de Acessibilidade.

+
+ +

Marcação de texto

+ +

Esta secção irá abranger alguns dos elementos básicos de HTML que irá utilizar para marcar texto.

+ +

Títulos

+ +

Elementos de título permitem especificar que determinadas partes do seu conteúdo são títulos (ou subtítulos) do conteúdo. Da mesma forma que um livro tem um título principal, títulos de capítulos e subtítulos, um documento HTML também os pode ter. HTML contém seis níveis de títulos, {{htmlelement("h1")}}–{{htmlelement("h6")}} mas geralmente usam-se no máximo 3 ou 4:

+ +
<h1>Título principal</h1>
+<h2>Título mais abrangente</h2>
+<h3>Subtítulo</h3>
+<h4>Sub-subtítulo</h4>
+ +

Tente agora acrescentar um título à sua página HTML mesmo por cima do seu elemento {{htmlelement("img")}}.

+ +

Parágrafos

+ +

Como já foi explicado, elementos {{htmlelement("p")}} servem para conter parágrafos; vai usá-los frequentemente quando marcar conteúdo textual:

+ +
<p>Isto é um único parágrafo</p>
+ +

Acrescente um ou mais parágrafos com a sua amostra de texto (conforme o artigo Qual será a aparência do seu site da Web?), diretamente por baixo do elemento {{htmlelement("img")}}.

+ +

Listas

+ +

Grande parte do conteúdo da web está em listas, e HTML tem elementos especiais para as mesmas. Marcar listas consiste sempre em pelo menos 2 elementos. As listas mais comuns são as listas ordenadas e não ordenadas:

+ +
    +
  1. Listas não ordenadas são listas em que a ordem dos elementos não é relevante, como uma lista de compras. São envoltas no elemento {{htmlelement("ul")}}.
  2. +
  3. Listas ordenadas são listas em que a ordem dos elementos é importante, como uma receita. São envoltas no elemento {{htmlelement("ol")}}.
  4. +
+ +

Cada artigo na lista é colocado dentro de um elemento {{htmlelement("li")}} (list item).

+ +

Por exemplo, se quisermos transformar parte deste trecho numa lista:

+ +
<p>Na Mozilla, somos uma comunidade global de tecnólogos, pensadores, e construtores que trabalham juntos ... </p>
+ +

Podemos modificar a marcação desta forma:

+ +
<p>Na Mozilla, somos uma comunidade global de</p>
+
+<ul>
+  <li>tecnólogos</li>
+  <li>pensadores</li>
+  <li>construtores</li>
+</ul>
+
+<p>que trabalham juntos ... </p>
+ +

Tente acrescentar uma lista ordenada ou não ordenada à sua página de exemplo.

+ +

Hiperligações

+ +

As hiperligações são muito importantes — são elas que tornam a internet na internet! Para acrescentar uma ligação, precisamos de um elemento simples — {{htmlelement("a")}} — cujo "a" abrevia "âncora". Para transformar texto no seu parágrafo numa ligação, siga estes passos:

+ +
    +
  1. Escolha algum texto. Escolhemos o texto "Manifesto da Mozilla".
  2. +
  3. Envolva o texto num elemento {{htmlelement("a")}}, assim: +
    <a>Manifesto da Mozilla</a>
    +
  4. +
  5. Dê ao elemento {{htmlelement("a")}} um atributo href, assim: +
    <a href="">Manifesto da Mozilla</a>
    +
  6. +
  7. Preencha o valor deste atributo com o endereço web para o qual quer ligar a hiperligação: +
    <a href="https://www.mozilla.org/pt-PT/about/manifesto/">Manifesto da Mozilla</a>
    +
  8. +
+ +

Pode obter resultados inesperados se omitir a parte do protocolo no início do endereço web (https:// ou http://). Depois de criar uma hiperligação, clique para assegurar que está a enviá-lo para onde é pretendido.

+ +
+

href pode, à primeira vista, parecer uma escolha obscura para o nome de um atributo. Se tiver dificuldades em lembrar-se dele, recorde que significa hypertext reference.

+
+ +

Agora, acrescente a hiperligação à sua página, se ainda não o fez.

+ +

Conclusão

+ +

Se seguiu todas as instruções nesta página, deve ter conseguido uma página que se assemelha à página em baixo (também pode vê-la aqui):
+
+ A web page screenshot showing a firefox logo, a heading saying mozilla is cool, and two paragraphs of filler text

+ +

Se ficou preso, pode comparar o seu trabalho com o exemplo do código terminado no GitHub.

+ +

Aqui, mal tocámos na superfície da linguagem HTML. Para descobrir mais, dirija-se ao nosso tópico sobre Aprender HTML.

+ +

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Lidar_com_ficheiros","Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web")}}

+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/index.html b/files/pt-pt/learn/getting_started_with_the_web/index.html new file mode 100644 index 0000000000..59a4431592 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/index.html @@ -0,0 +1,65 @@ +--- +title: Primeiros passos na Web +slug: Learn/Comecar_com_a_Web +tags: + - Beginner + - CSS + - Desenho + - Guía + - HTML + - 'I10n:priority' + - Index + - publicação + - teoria +translation_of: Learn/Getting_started_with_the_web +--- +
{{LearnSidebar}}
+ +
+

Iniciação à Web é uma série concisa introduzindo-lhe os aspetos práticos do desenvolvimento da Web. Irá configurar as ferramentas necessárias para criar uma página da Web simples e publicar o seu próprio código simples.

+
+ +

A história do seu primeiro site da Web

+ +

É muito trabalho para criar um site da Web profissional, por isso, se é novo no desenvolvimento da Web, nós encorajamos que comece por uma coisa pequena. Não irá criar outro Facebook de imediato, mas não é difícil ter o seu próprio site da Web simples on-line. Vamos lá começar.

+ +

Ao trabalhar com os artigos listados abaixo em ordem, irá passar do nada para ter a sua primeira página da Web on-line. Vamos lá!

+ +

Instalar software básico

+ +

Quando se trata de ferramentas para criar um site da Web, há muito a escolher. Se está apenas a começar, pode ficar confuso com a variedade de editores de código, estruturas e ferramentas de teste disponíveis. Em Instalar software básico, nós mostramos-lhe passo-a-passo como instalar apenas o software necessário para iniciar um desenvolvimento da web básico.

+ +

Qual será a aparência do seu site da Web?

+ +

Antes de começar a escrever o código do seu site da Web, deverá planeá-lo primeiro. Que informação está a apresentar? Que tipo de letra e cores está a utilizar? Como é que será apresentado o seu site da Web? Nós descrevemos um método simples que pode seguir para planear o conteúdo e o desenho do seu site.

+ +

Lidar com ficheiros

+ +

Um site consiste em muitos ficheiros: conteúdo de texto, código, stylesheets, conteúdo de média, e mais. Quando constrói um site, precisa de organizar os seus ficheiros e certificar-se que podem comunicar uns com os outros. Lidar com ficheiros explica como criar uma estrutura para os ficheiros do seu site e quais as questões que devem ser do seu conhecimento.

+ +

Básicos de HTML

+ +

Hypertext Markup Language (HTML) é o código que usa para estruturar, dar significado, e propósito ao seu conteúdo de web. Por exemplo, é o meu conteúdo um conjunto de parágrafos, ou uma lista de pontos? Tenho imagens inseridas na minha página? O HTML - Essencial fornece informação suficiente para o familiarizar com o HTML, sem o sobrecarregar.

+ +

Básicos de CSS

+ +

Cascading Stylesheets (CSS) é o código que usa para decorar o seu site. Por exemplo, quer o texto colorido negro ou vermelho? Onde desenhar o conteúdo no ecrã? Que imagens de fundo e cores deve usar para decorar o site? CSS - Essencial leva-o através do que precisa para começar.

+ +

Básicos de JavaScript

+ +

JavaScript é a linguagem de programação que utiliza para adicionar funcionalidades interativas ao seu website, por exemplo, jogos, coisas que acontecem quando botões são premidos ou quando dados são introduzidos em formulários, efeitos de estilo dinâmicos, animação, e muito mais. JavaScript - Essencial dá-lhe uma ideia do que é possível com esta linguagem emocionante, e como começar.

+ +

Publicar o seu site da Web

+ +

Após de escrever o código e organizar os ficheiros que compõem o seu site, tem de o colocar online para que as pessoas o possam encontrar. "Publicar o seu site da Web" descreve como colocar o seu código de amostra simples online com o mínimo de esforço.

+ +

Como é que funciona a Web

+ +

Quando acede ao seu site favorito, muitas coisas complicadas acontecem em segundo plano de que poderá não ter conhecimento. Como funciona a Web descreve o que acontece quando visualiza uma página da web no seu computador.

+ +

Consulte também

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html b/files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html new file mode 100644 index 0000000000..ebc5ddd3e3 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html @@ -0,0 +1,165 @@ +--- +title: Instalar software básico +slug: Learn/Comecar_com_a_Web/Installing_basic_software +tags: + - Aprender + - Beginner + - Configurar + - Ferramentas + - Mecânicas da Web + - Navegador + - editor de texto + - 'l10n:priority' +translation_of: Learn/Getting_started_with_the_web/Installing_basic_software +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web")}}
+ +
+

Neste artigo, mostramos-lhe de que ferramentas precisa para desenvolvimento da Web básico, e como instalá-las corretamente.

+
+ +

Que ferramentas é que os profissionais utilizam?

+ + + +

De que ferramentas realmente preciso, de momento?

+ +

Parece uma lista assustadora, mas felizmente pode começar a desenvolver para a web sem saber nada sobre a maioria daquelas coisas. Neste artigo instalamos o mínimo dos mínimos — editor de texto e navegadores modernos.

+ +

Instalar um editor de texto

+ +

Provavelmente já tem um editor de texto simples no seu computador. O Windows inclui, de fábrica, o Bloco de Notas (Notepad) e o macOS vem com o Editor de Texto (TextEdit). Em distribuições de Linux, varia; Ubuntu vem com o gedit.

+ +

Para desenvolvimento na Web, há alternativas mais completas que o Notepad ou TextEdit. Propomos-lhe começar com o Visual Studio Code, um editor gratuito que oferece pré-visualização em tempo real e sugestões de código.

+ +
+

Não confundir Notepad (Bloco de Notas) com Wordpad! Este último é equiparável a programas de Office, que não são adequados para escrever código de computador, como já foi referido. 

+
+ +

Instalar navegadores da Web modernos

+ +

Antes de avançar, deve escolher uns navegadores que possa ter à mão para realizar testes. Escolha o seu sistema operativo e faça clique nos links para descarregar o programa de instalação respetivo dos seus navegadores preferidos:

+ + + +
+

Internet Explorer (IE) não é compatível com funções da web modernas e pode não conseguir correr o seu projeto. Tipicamente não será necessário fazer os seus projetos compatíveis com o IE, pois muito poucas pessoas ainda a utilizam - certamente não se preocupe muito com isso enquanto está a aprender. Por vezes pode deparar-se com um projeto que requer apoio para o mesmo.

+
+ +

Instalar um servidor da Web local

+ +

Alguns exemplos terão de ser executados através de um servidor da Web para funcionar com sucesso. Pode aprender como fazer isto no artigo como configurar um servidor local de testes?

+ +
{{NextMenu("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web")}}
+ +

Neste módulo

+ + + +
+ + + + + +
diff --git a/files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html b/files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html new file mode 100644 index 0000000000..fec3caaf51 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html @@ -0,0 +1,413 @@ +--- +title: JavaScript - Essencial +slug: Learn/Comecar_com_a_Web/Elementar_de_JavaScript +tags: + - Aprender + - Beginner + - CodingScripting + - JavaScript + - Web + - 'l10n:priority' +translation_of: Learn/Getting_started_with_the_web/JavaScript_basics +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
+ +
+

JavaScript é uma linguagem de programação que dá interatividade ao seu website (sob a forma, por exemplo, de jogos, respostas quando os botões são pressionados ou quando são inseridos dados nos formulários, estilos dinâmicos ou animações). Este artigo faz uma introdução a esta linguagem excitante e dá-lhe uma ideia do que é possível.

+
+ +

O que é JavaScript, realmente?

+ +

{{Glossary("JavaScript")}} (abreviado "JS") é uma {{Glossary("Dynamic programming language", "linguagem de programação dinâmica")}} completa que, quando é aplicada a um documento {{Glossary("HTML")}}, produz interatividade dinânimca no website. Foi inventada por Brendan Eich, co-fundador do projeto Mozilla, da Mozilla Foundation, e da Mozilla Corporation.

+ +

JavaScript é incrivelmente versátil. Pode começar em ponto pequeno, com carrosséis, galerias de imagens, layouts flutuantes, e mensagens quando se prime um botão. Depois de ganhar experiência, será capaz de criar jogos, gráficos 2D e 3D animados, aplicações completas conduzidas por bases-de-dados e muito mais!

+ +

JavaScript é relativamente compacta e muito flexível. Os programadores já escreveram uma grande variedade de ferramentas sobre o núcleo desta linguagem, o que abriu portas a uma vasta quantidade de funcionalidade extra com esforço mínimo. Isto inclui:

+ + + +

Uma vez que este artigo é apenas uma introdução ligeira a JavaScript, não vamos confundi-lo com detalhes sobre a diferença entre JavaScript puro e as ferramentas enumeradas em cima. Poderá aprender esse detalhe mais tarde, na nossa área de aprendizagem de JavaScript, e no resto da MDN.

+ +

De seguida vamos introduzi-lo a alguns aspetos do núcleo da linguagem (JS puro, sem ferramentas), e também vai jogar com algumas funcionalidades da API do navegador. Divirta-se!

+ +

Um exemplo "olá mundo"

+ +

A secção anterior deve parecer mesmo empolgante — JavaScript é uma das tecnologias web mais animadas, e à medida que se torna bom a usá-la, os seus sites entrarão numa nova dimensão de poder e creatividade.

+ +

Contudo, ficar confortável com JavaScript é um pouco mais difícil do que ficar confortável com HTML e CSS. Terá que começar com projetos pequenos e prosseguir com passos pequenos e consistentes. Para começar, vamos mostrar como adicionar JavaScript básico à sua página, criando um exemplo "hello world" / "olá mundo!" (o padrão de exemplos básicos de programação).

+ +
+

Importante: Se não tem seguido o resto deste curso, descarregue este exemplo de código e utilize-o como ponto de partida.

+
+ +
    +
  1. Primeiro, crie uma pasta "scripts" (sem aspas) na raíz do seu site de testes. Depois, dento desta pasta, crie um ficheiro chamado main.js.
  2. +
  3. A seguir, no ficheiro index.html introduza o elemento seguinte numa linha nova mesmo antes da etiqueta de fechi </body>: +
    <script src="scripts/main.js"></script>
    +
  4. +
  5. Basicamente isto faz o mesmo que o elemento {{htmlelement("link")}} faz com CSS — aplica o código JavaScript à página, para que surta efeito no HTML (juntamente com o CSS, e outros recursos da página).
  6. +
  7. Agora adicione o código seguinte ao ficheiro main.js: +
    var myHeading = document.querySelector('h1');
    +myHeading.textContent = 'Olá mundo!';
    +
  8. +
  9. Finalmente, certifique-se que guardou as alterações aos ficheiros HTML e JavaScript, e carregue o ficheiro index.html no navegador. Deverá ver algo como:
  10. +
+ +
+

Nota: O motivo pelo qual pusemos o elemento {{htmlelement("script")}} no fim do ficheiro HTML é que os elementos são carregados pelo navaegador na ordem em que aparecem no ficheiro. Se o JavaScript é carregado primeiro e tem que afetar o HTML por baixo dele, pode não funcionar, já que o código JavaScript seria carregado antes do HTML que era suposto modificar. Assim, colocar o JavaScript no fim do ficheiro HTML costuma ser a melhor estratégia.

+
+ +

O que aconteceu?

+ +

O texto do título foi mudado para "Hello world!", utilizando JavaScript. Isto foi feito com a função {{domxref("Document.querySelector", "querySelector()")}} para obter uma referência do título e guardá-la numa variável myHeading. Isto é semelhante ao que fizémos com seletores CSS. Quando se pretende fazer algo com um elemento, há que selecioná-lo primeiro.

+ +

Depois, muda-se o valor da propriedade {{domxref("Node.textContent", "textContent")}} da variável myHeading (a qual representa o conteúdo textual do título) para "Olá Mundo!".

+ +
+

Nota: Ambas as funções utilizadas fazem parte da API do Document Object Model (DOM) , o qual permite manipular documentos HTML.

+
+ +

Curso intensivo das bases da linguagem

+ +

Vamos explicar algumas funcionalidades fundamentais da linguagem JavaScript, para permitir uma melhor compreensão de como a mesma funciona. Note que estas funcionalidades são comuns a todas as linguagens de programação, por isso, se dominar estes fundamentos, estará no bom caminho para programar praticamente qualquer coisa!

+ +
+

Importante: Neste artigo, tente introduzir os exemplos de código na consola JavaScript para ver o que acontece. Para mais detalhes sobre a consola JavaScript, veja o artigo Descobrir as ferramentas de desenvolvimentos do navegador.

+
+ +

Variáveis

+ +

{{Glossary("Variable", "Variáveis")}} são "recipientes" em que pode guardar valores. Comece por declarar a variável com a palavra-chave var, seguida de qualquer nome que lhe queira dar:

+ +
var minhaVariavel;
+ +
+

Nota: O ponto e vírgula indica onde termina a instrução; apenas é estritamente necessário quando pretende separar instruções numa só linha. Contudo, algumas pessoas acham que é boa prática colocar este sinal no fim de cada instrução. Há mais regras sobre quando se deve ou não utilizá-lo — veja o artigo Your Guide to Semicolons in JavaScript (inglês) para obter mais detalhes.

+
+ +
+

Nota: O nome da varíavel pode ser quase tudo, mas há restrições (veja este artigo sobre regras para dar nome às variáveis (inglês)). Se não tem a certeza, pode verificar o nome da sua variável para assegurar que é válido.

+
+ +
+

Nota: JavaScript é sensível a maiúsculas — minhaVariavel é uma variável diferente de minhavariavel. Se tiver encontrar problemas depois de escrever p código, verifique as maiúsculas e minúsculas!

+
+ +

Depois de declarar a variável, pode atribuir-lhe um valor:

+ +
minhaVariavel = 'Bob';
+ +

Pode efetuar ambas as operações com uma só instrução:

+ +
var myVariable = 'Bob';
+ +

O valor é obtido simplesmente escrevendo o nome da variável:

+ +
myVariable;
+ +

Depois de lhe dar um valor, pode optar por mudá-lo mais tarde:

+ +
var minhaVariavel = 'Bob';
+minhaVariavel = 'Steve';
+ +

Atenção que as variáveis podem ter valores com diferentes tipos de de dados:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
VariávelExplicaçãoExemplo
{{Glossary("String")}}Uma sequência de texto conhecido como string ou cadeia de caracteres. Para indicar que é uma string, envolve-se em plicas '.var minhaVariavel = 'Bob';
{{Glossary("Number")}}Um número. Não tem plicas em sua volta.var minhaVariavel = 10;
{{Glossary("Boolean")}}Valor que ou é verdadeiro ou falso. As palavras true e false são palavras-chave em JS, e não precisam de plicas.var minhaVariavel = true;
{{Glossary("Array")}}Estrutura que permite guardar múltiplos valores numa só referência.var minhaVariavel = [1,'Bob','Steve',10];
+ Cada elemento da Array é referido desta forma (começa em zero):
+ myVariable[0], myVariable[1], etc.
{{Glossary("Object")}}Pode ser qualquer coisa. Em JavaScript, tudo é um objeto e pode guardar-se numa variável. Mantenha isto em mente enquanto aprende.var minhaVariavel = document.querySelector('h1');
+ Assim como todos os exemplos anteriores.
+ +

Então para que precisamos das variáveis? Bem, são necessárias para qualquer tarefa interessante em programação. Se não houvesse valores que mudassem, não seria possível criar nada que fosse dinâmico, como personalizar uma mensagem de boas vindas ou mudar a imagem que se está a ver numa galeria.

+ +

Comentários

+ +

Pode deixar comentários no seu código JavaScript, tal como em CSS:

+ +
/*
+Tudo entre estas marcas é um comentário.
+*/
+ +

Se o comentário não contiver quebras de linha, deve ser mais fácil utilizar duas barras, assim:

+ +
// Isto é um comentário
+
+ +

Operadores

+ +

Um {{Glossary("operator")}} é um símbolo matemático que produz o resultado de uma operação entre dois valores (que podem ser variáveis). Na tabela seguinte constam alguns dos operadores mais simples, juntamente com alguns exemplos que pode experimentar na consola de JavaScript.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperadorExplicaçãoSímbolo(s)Exemplo
AdiçãoSoma números ou junta duas strings.+6 + 9;
+ "Hello " + "world!";
Subtração, Multiplicação, DivisãoComportam-se com esperado em aritmética.-, *, /9 - 3;
+ 8 * 2; // em JS, o sinal de "vezes" é um asterisco
+ 9 / 3;
AtribuiçãoJá vimos isto: atribui um valor a uma variável.=var minhaVariavel = 'Bob';
IgualdadeFaz um teste para verificar se dois valores são iguais e retorna um valor booleano (true/false).===var minhaVariavel = 3;
+ minhaVariavel === 4;
Negação, DesigualdadeDevolve o valor logicamente oposto, ou seja, torna o verdadeiro em falso e vice-versa. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal.!, !== +

The basic expression is true, but the comparison returns false because we've negated it:

+ +

var myVariable = 3;
+ !(myVariable === 3);

+ +

Verificar se "a minhaVariavel NÃO é igual a 3". Retorna false porque minhaVariavel é de facto igual a 3.

+ +

var minhaVariavel = 3;
+ minhaVariavel !== 3;

+
+ +

Há muito mais operadores a explorar, mas por agora basta. Veja uma lista completa no artigo Expressões e operadores.

+ +
+

Nota: Misturar tipos de dados pode ter resultados estranhos, então certifique-se que está a utilizar as variáveis corretamente e que os resultados estão dentro do esperado. Por exemplo, introduza "35" + "25" na consola. Porque é que não faz a soma dos números? Porque as aspas tornam os números em strings, então em vez de somar, fez a concatenção das strings. Se introduzir, 35 + 25 já obterá o resultado correto.

+
+ +

Condições

+ +

Condições são estruturas de código que permitem, em função do valor lógico (verdadeiro/falso) de uma expressão, executar código de entre várias alterantivas. Uma forma comum de uma condiçães é a instrução if ... else (se ... senão). Por exemplo:

+ +
var gelado = 'chocolate';
+if (gelado === 'chocolate') {
+  alert('Viva, adoro gelado de chocolate!');
+} else {
+  alert('Ohhhh, mas o meu favorito é chocolate...');
+}
+ +

A expressão dentro de parênteses em if ( ... ) é a condição — utilza o operador de igualdade (como foi descrito em cima) para comparar a variável gelado com a string 'chocolate' e assim verificar se são iguais. Caso esta comparação devolva true, é executado o primeiro bloco de código. Se não for verdadeira, não é executado o primeiro mas sim o segundo bloco de código, depois da instrução else.

+ +

Funções

+ +

{{Glossary("Function", "Functions")}} são uma maneira de juntar uma funcionalidade ou um conjunto instruções que se pretende reutilizar. Quando se pretende utilizar esta funcionalidade, chama-se a função pelo nome, em vez de voltar a escrever o código em cada utilização. Já pudémos ver a utilização de algumas funções, por exemplo:

+ +
    +
  1. +
    var minhaVariavel = document.querySelector('h1');
    +
  2. +
  3. +
    alert('hello!');
    +
  4. +
+ +

Estas funções, document.querySelector e alert, estão incluídas no navegador para serem utilizadas sempre que necessário.

+ +

Quando vê algo que parece um nome de uma variável mas tem parênteses à direita— () —  é provavelmente uma função. As funções costumam possuir {{Glossary("Argument", "arguments")}} — dados de que necessitam para fazer o seu trabalho. Estes são passados dentros dos parênteses, separados por vírgulas quando há mais do que um.

+ +

Por exemplo, a função alert() faz aparecer um "pop-up" na janela do navegador, mas é preciso dar-lhe uma string como argumento para que ela saiba o que escrever.

+ +

E as boa notícia é que pode definir as suas próprias funções. Neste exemplo escrevemos uma função simples que aceita dois argumentos numéricos e multiplica-os:

+ +
function multiplicar(num1,num2) {
+  var resultado = num1 * num2;
+  return resultado;
+}
+ +

Tente declarar esta função na consola e depois testá-la com vários argumentos. Por exemplo:

+ +
multiplicar(4, 7);
+multiplicar(20, 20);
+multiplicar(0.5, 3);
+ +
+

Nota: A instrução return diz ao navegador para devolver/retornar a variável result para fora da função para que o seu valor possa ser utilizado. Isto é necessário porque variáveis definidas dentro das funções só estão disponíveis dentro dessas funções — a essa particularidade chama-se o âmbito da variável ({{Glossary("Scope", "scoping")}}). (Leia mais sobre âmbito de variáveis)

+
+ +

Eventos

+ +

Num site, interactividade a sério precisa de eventos. Eles são estruturas de código que esperam que algo aconteça no navegador e respondem executando código. O exemplo mais óbvio é o evento de clique, que é enviado pelo navegador quando se clica em algo com o rato. Para demonstrar, introduza isto na sua consola, e depois clique na página atual:

+ +
document.querySelector('html').onclick = function() {
+    alert('Ai! Para de me picar!');
+}
+ +

Há muitas maneiras de associar um evento a um elemento. Aqui, selecionamos o elemento {{htmlelement("html")}}, atribuímos à sua propriedade onclick o manuseador do evento (event handler), que neste caso é uma função anónima (sem nome), que contém o código que queremos que o evento de clique execute.

+ +

Note que isto:

+ +
document.querySelector('html').onclick = function() {};
+ +

É equivalente a isto:

+ +
var myHTML = document.querySelector('html');
+myHTML.onclick = function() {};
+ +

Só que o primeiro é mais curto.

+ +

Supercarregar o nosso site-exemplo

+ +

Agora que que já vimos as bases de JavaScript, vamos acrescentar umas funcionalidades fixes ao nosso site para ver o que é possível.

+ +

Acrescentar um alterador de imagens

+ +

Nesta secção, vamos acrescentar uma imagem adicional ao nosso site com funções da API da DOM, utilizando JavaScript para mudar alternar entre as duas imagens quando se clica nelas.

+ +
    +
  1. Primeiro, encontre outra imagem que goste de ter no seu site. Certifique-se que o tamanho é o mais próximo possível da primeira imagem.
  2. +
  3. Guarde-a na pasta images.
  4. +
  5. Mude o nome para "firefox2.png" (sem aspas).
  6. +
  7. Vá ao ficheiro main.js, e introduza o seguinte código JavaScript. (Apague o código do "olá mundo", se ainda lá estiver) +
    var myImage = document.querySelector('img');
    +
    +myImage.onclick = function() {
    +    var mySrc = myImage.getAttribute('src');
    +    if(mySrc === 'images/firefox-icon.png') {
    +      myImage.setAttribute('src','images/firefox2.png');
    +    } else {
    +      myImage.setAttribute('src','images/firefox-icon.png');
    +    }
    +}
    +
  8. +
  9. Guarde todos os ficheiros e carregue o index.html no navegador. Agora, quando clicar sobre a imagem, ela deve mudar para a outra!
  10. +
+ +

Guardou-se uma referência para o elemento {{htmlelement("img")}} na variável myImage. Depois, atribui-se à propriedade onclick desta variável uma função anónima. Agora, sempre que se clica no elemento:

+ +
    +
  1. Obtem-se o valor do atributo src.
  2. +
  3. Utiliza-se uma condição para averiguar se o valor do mesmo é igual ao caminho da primeira imagem: +
      +
    1. Se for, muda-se para o caminho da 2ª imagem, o que a obriga a ser carregada no elemento {{htmlelement("img")}}.
    2. +
    3. Se não for (e portanto, já se trocaram as imagens), o valor de src volta a ser o caminho da imagem original.
    4. +
    +
  4. +
+ +

Dar uma mensagem de boas-vindas personalizada

+ +

De seguida vamos acrescentar mais um pouco de código, que vai mudar o título da página para uma mensagem de boas-vindas personalizada quando o utilizador navega no site pela primeira vez. A mesma vai persistir, mesmo que o utilizador saia do site e volte mais tarde — vamos guardá-la com a API de Web Storage. Também vamos acrescentar opção de mudar de utilizador e, com o mesmo, a mensagem de boas-vindas sempre que for necessário.

+ +
    +
  1. Em index.html, acrescente esta linha logo antes do elemento {{htmlelement("script")}}: + +
    <button>Change user</button>
    +
  2. +
  3. Em main.js, coloque o código seguinte no fim do ficheiro, tal como está escrito — isto obtem referências ao novo botão e o título, e guarda-os em variáveis: +
    var myButton = document.querySelector('button');
    +var myHeading = document.querySelector('h1');
    +
  4. +
  5. Agora acrescente a função em baixo para estabelecer a mensagem personalizada — por agora não faz nada, mas já vamos tratar disso: +
    function setUserName() {
    +  var myName = prompt('Por favor introuduza o seu nome.');
    +  localStorage.setItem('name', myName);
    +  myHeading.textContent = 'Mozilla is cool, ' + myName;
    +}
    + Este função faz uso da função prompt(), que mostra uma caixa de diálogo, semelhante a alert(). Mas a prompt() pede ao utilizador que introduza dados, que armazena numa variável depois que o mesmo faça OK. Neste caso, pedimos ao utilizador que introduza o seu nome. Depois, recorremos à API chamada localStorage, que nos permite guardar dados no navegador para os obter mais tarde. Utilizamos a função setItem() para criar e guardar o artigo 'name', e dando-lhe o valor da variável myName, a qual contém o nome introduzido pelo utilizador. Finalmente, mudamos o textContent do título para uma string, à qual concatenamos o nome recentemente armazenado.
  6. +
  7. Próximo: acrescente este bloco if ... else — podemos chamar-lhe código de iniciação, já que define a estrutura da aplicação quando é carregada pela primeira vez: +
    if(!localStorage.getItem('name')) {
    +  setUserName();
    +} else {
    +  var storedName = localStorage.getItem('name');
    +  myHeading.textContent = 'Mozilla is cool, ' + storedName;
    +}
    + Este bloco começa por utilizar o operador de negação ("não-lógico", representado pelo !) para averiguar se o dado name existe. Se não existir, a função setUserName() é utilizada para o criar. Se existe (ou seja, o utilizador introduziu-o numa visita anterior), recuperamos o nome armazenado com getItem() e mudamos textContent do título para a string, mais o nome do utilizador, da mesma forma que fizémos em setUserName().
  8. +
  9. Finalmente, coloque o manuseador do evento onclick no botão, como se mostra em baixo. Quando se clica no botão, é chamada a função setUserName(). Isto permite ao utilizador introduzir um novo nome, sempre que desejar, ao premir o botão: +
    myButton.onclick = function() {
    +  setUserName();
    +}
    +
    +
  10. +
+ +

Agora, sempre que visitar o site, vai pedir-lhe o seu nome de utilizador, e depois mostrar a mensagem personalizada. Pode mudar o nome sempre que quiser ao premir o botão. Como bónus, já que o nome está guardado em localStorage (armazenamento local), persiste mesmo que o site seja fechado, e mantém a mensagem quando se voltar ao site!

+ +

Conclusão

+ +

Se seguiu as instruções neste artigo, o resultado final deve ser uma página semelhante à que vê na imagem em baixo (pode ver  a nossa versão aqui):

+ +

+ +

Caso se tenha perdido, pode comparar o código que escreveu com o nosso exemplo terminado no GitHub.

+ +

Este artigo mal rasou a superfície de JavaScript. Se gostou de brincar e deseja continuar a aprender, dirija-se ao nosso tópico de aprendizegem de JavaScript.

+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html b/files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html new file mode 100644 index 0000000000..7e99504b95 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html @@ -0,0 +1,125 @@ +--- +title: Publicar o seu site na Web +slug: Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web +tags: + - Aprender + - Beginner + - CodingScripting + - FTP + - GitHub + - Google App Engine + - Servidor de Web + - Web + - publicar +translation_of: Learn/Getting_started_with_the_web/Publishing_your_website +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web/Como_funciona_a_Web", "Learn/Comecar_com_a_Web")}}
+ +
+

Assim que terminar de escrever o código e organizar os ficheiros que compõem o seu sire da web, precisa de colocar tudo online para que pessoas o possam encontrar. Este artigo explica como colocar o seu código de amostra online com pouco esforço.

+
+ +

Quais são as opções?

+ +

A publicação de um site na web é um tema complexo porque há muitas maneiras de o abordar. Este artigo não tenta documentar todos os métodos possíveis. Em vez disso, explica as vantagens e desvantagens de três abordagens que são práticas para os principiantes. Depois, passa por um método que pode funcionar de imediato para muitos leitores.

+ +

Encontrar hospedagem na web e um nome de domínio

+ +

Para ter mais controlo sob o conteúdo e a aparência dum site, a maioria das pessoas escolhe comprar hospedagem na web e um nome de domínio:

+ + + +

Muitos sites profissionais escolhem este modo para pôr o seu site online.

+ +

Além disso, precisará de um programa {{Glossary("FTP", "File Transfer Protocol (FTP)")}} (ver How much does it cost: software para mais detalhes) para transferir os ficheiros do site para o servidor. Os programas FTP variam muito, mas geralmente, tem de se ligar ao seu servidor web utilizando os detalhes fornecidos pela sua empresa de hospedagem (normalmente nome de utilizador, palavra-passe, nome de anfitrião). Depois, o programa mostra-lhe os seus ficheiros locais e os ficheiros do servidor web em duas janelas, e fornece-lhe uma forma de transferir ficheiros para trás e para a frente.

+ +

+ +

Dicas para encontrar hospedagem na web e um nome de domínio

+ + + +

Usar uma ferramenta online

+ +

Algumas ferramentas permitem publicar o seu site online:

+ + + +

Estas opções são tipicamente grátis, mas é possível você acabar por precisar mais que as funções que elas oferecem.

+ +

Usar um IDE online

+ +

Existem várias aplicações web que imitam um ambiente de desenvolvimento de website, permitindo-lhe introduzir HTML, CSS e JavaScript, e depois mostrar o resultado desse código como um website — tudo num único separador do navegador. Em geral, estas ferramentas são relativamente fáceis de manusear, ótimas para aprender, boas para partilhar código (por exemplo, se quiser partilhar uma técnica com ou pedir ajuda de depuração a colegas num escritório diferente), e gratuitas (para funcionalidades básicas). Hospedam a sua página num endereço da web único. No entanto, as funcionalidades são limitadas, e estas aplicações normalmente não fornecem espaço de alojamento para ativos (como imagens).

+ +

Experimente usar as seguintes IDEs para descobrir qual é a melhor para si:

+ + + +

+ +

Publicar via GitHub

+ +

Agora vejamos como facilmente publicar o seu site através do GitHub Pages.

+ +
    +
  1. Primeiro, inscreva se no GitHub e confirme o seu endereço eletrónico.
  2. +
  3. A seguir, a crie um repositório para guardar os seus ficheiros.
  4. +
  5. Nesta página, na caixa Repository name, escreva username.github.io, onde username é o seu nome de utilizador. Por exemplo, Bob Smith iria introduzir bobsmith.github.io na caixa. Selecione a caixa "Initialize this repository with a README", e carregue "Create repository".
  6. +
  7. Arraste os conteúdos da sua pasta para o website, para dentro do repositório. Depois carregue em Commit changes.
    + +
    +

    Nota: Certifique se que a sua pasta contém o ficheiro index.html.

    +
    +
  8. +
  9. +

    Navegue no seu navegador até username.github.io para ver o seu website online. Por exemplo, para o nome de utilizador chrisdavidmills, vai a chrisdavidmills.github.io.

    + +
    +

    Nota: Pode demorar alguns minutos para que o seu site esteja live. Se o seu site não for visível imediatamente, espere por uns minutos e tente novamente.

    +
    +
  10. +
+ +

Para aprender mais, veja GitHub Pages Help.

+ +

Leitura complementar

+ + + +

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web/Como_funciona_a_Web", "Learn/Comecar_com_a_Web")}}

+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html b/files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html new file mode 100644 index 0000000000..928a960b97 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html @@ -0,0 +1,174 @@ +--- +title: A Web e os padrões da Web +slug: Learn/Comecar_com_a_Web/A_web_e_os_padroes_da_web +tags: + - Aprender + - Beginner + - Front-end + - Normas da Web + - Padrões da Web + - Web +translation_of: Learn/Getting_started_with_the_web/The_web_and_web_standards +--- +

{{learnsidebar}}

+ +

Este artigo fornece informação útil sobre a Web - como surgiu, o que são as tecnologias padrão da Web, como trabalham em conjunto, porque é que web developer é uma excelente carreira a escolher, e que melhores práticas irá aprender através do curso.

+ +

História resumida da Web

+ +

Vamos manter isto muito breve, pois existem relatos muito (mais) detalhados da história da web lá fora, aos quais faremos referência mais tarde (tente também procurar por "história da web" no seu motor de busca favorito e veja o que obtém, se estiver interessado em mais detalhes).

+ +

No final da década de 1960, o exército dos EUA desenvolveu uma rede de comunicação chamada ARPANET. Esta pode ser considerada uma precursora da Web, uma vez que funcionava na {{Interwiki("wikipedia", "Comutação de pacotes", "comutação de pacotes")}}, e incluía a primeira implementação do conjunto de protocolos {{Interwiki("wikipedia", "TCP/IP", "TCP/IP")}}. Estas duas tecnologias formam a base da infra-estrutura sobre a qual a Internet está construída.

+ +

Em 1980, Tim Berners-Lee (frequentemente referido como TimBL) escreveu um programa de caderno de notas chamado ENQUIRE, que apresentava o conceito de ligações entre os diferentes nódulos. Soa familiar?

+ +

Avançando para 1989, e a TimBL escreveu Information Management: A Proposal e HyperText at CERN; estas duas publicações em conjunto forneceram o pano de fundo para a forma como a web funcionaria. Receberam interesse suficiente para convencer os chefes do TimBL a permitir-lhe avançar e criar um sistema global de hipertexto.

+ +

No final de 1990, TimBL tinha criado todas as coisas necessárias para executar a primeira versão da web - HTTP, HTML, o primeiro navegador web, que se chamava {{Interwiki("wikipedia", "WorldWideWeb", "WorldWideWeb")}}, um servidor HTTP, e algumas páginas web para ver.

+ +

Nos anos que se seguiram, a web explodiu, com vários navegadores a serem lançados, milhares de servidores web a serem criados, e milhões de páginas web a serem criadas. OK, este é um resumo muito simples do que aconteceu, mas prometi-vos um breve resumo.

+ +

Um último dado significativo a partilhar é que em 1994, o TimBL fundou o {{Interwiki("wikipedia", "W3C", "World Wide Web Consortium")}} (W3C), uma organização que reúne representantes de muitas empresas tecnológicas diferentes para trabalharem em conjunto na criação de especificações tecnológicas para a web. Depois disso seguiram-se outras tecnologias, tais como CSS e JavaScript, e a web começou a parecer-se mais com a web que conhecemos hoje.

+ +

Os padrões da Web

+ +

As normas / padrões da web são as tecnologias que utilizamos para construir websites. Estas normas existem como longos documentos técnicos chamados especificações, que detalham exactamente como a tecnologia deve funcionar. Estes documentos não são muito úteis para aprender a utilizar as tecnologias que descrevem (é por isso que temos sites como a MDN Web Docs), mas em vez disso destinam-se a ser utilizados por engenheiros de software para implementar estas tecnologias (geralmente em navegadores).

+ +

Por exemplo, o HTML Living Standard descreve exactamente como o HTML (todos os elementos HTML, e as suas APIs associadas, e outras tecnologias circundantes) deve ser implementado.

+ +

As normas Web são criadas por organismos de normas — instituições que convidam grupos de pessoas de diferentes empresas tecnológicas a juntarem-se e acordarem sobre a melhor forma de como as tecnologias devem funcionar para cumprir todos os seus casos de utilização. O W3C é o organismo de normas Web mais conhecido, mas existem outros como o WHATWG (que foi responsável pela modernização da linguagem HTML), ECMA (que publica a norma para ECMAScript, na qual o JavaScript se baseia), Khronos (que publica tecnologias para gráficos 3D, como o WebGL), e outros.

+ +

Standards "abertos"

+ +

Um dos aspetos chave das normas web, que o TimBL e o W3C acordaram desde o início, é que a web (e as tecnologias web) devem ser livres de contribuir e utilizar, e não sobrecarregadas por patentes / licenciamento. Portanto, qualquer pessoa pode escrever o código para construir um website gratuitamente, e qualquer pessoa pode contribuir para o processo de criação de normas, onde as especificações são escritas.

+ +

Porque as tecnologias web são criadas abertamente, numa colaboração entre várias empresas, isso significa que nenhuma empresa as consegue controlar, que é fantástico. Não se quer que uma única empresa decida subitamente colocar a web inteira atrás de uma paywall, ou lançar uma nova versão de HTML que todos têm de comprar para continuar a fazer websites, ou pior ainda, decidindo apenas que já não estão interessados e simplesmente desligando a web.

+ +

Isto permite que a web continue a ser um recurso público disponível gratuitamente.

+ +

Não quebre a web

+ +

Outra frase que ouvirá em torno das normas abertas da web é "não quebre a web" — a ideia é que qualquer nova tecnologia web que seja introduzida deve ser retro compatível com o que existia antes (ou seja, os antigos websites continuarão a funcionar), e com o que existe atualmente (as futuras tecnologias, por sua vez, serão compatíveis com o que temos atualmente). Ao percorrer o material de aprendizagem aqui apresentado, começará a aprender como isto se torna possível com algum trabalho de conceção e implementação muito inteligente.

+ +

Ser um web developer é bom

+ +

A indústria da web é um mercado muito atrativo para entrar se estiver à procura de um emprego. Números recentemente publicados dizem que existem atualmente cerca de 19 milhões de web developers no mundo, e esse número é previsto mais que dobrar na próxima década. E, ao mesmo tempo, há uma escassez de competências na indústria — portanto, que melhor altura para aprender a desenvolvimento web?

+ +

No entanto, nem tudo é brincadeira — construir sites é uma atividade mais complicada do que costumava ser, e terá de dedicar algum tempo ao estudo de todas as diferentes tecnologias que precisa de utilizar, todas as técnicas e melhores práticas que precisa de conhecer, e todos os padrões típicos que será necessário implementar. Vai levar alguns meses para começar realmente a ser proficiente, e depois terá de continuar a aprender para que o seu conhecimento se mantenha atualizado com todas as novas ferramentas e funcionalidades que aparecem na plataforma web, e continuar a praticar e a aperfeiçoar a sua arte.

+ +

A única constante é a mudança.

+ +

Isto parece-lhe difícil? Não se preocupe — o nosso objetivo é dar-lhe tudo o que precisa de saber para começar, e as coisas ficarão mais fáceis. Assim que aceitar a constante mudança e incerteza da web, começará a divertir-se. Como parte da comunidade web, terá uma rede de contactos e material útil para o ajudar, e começará a desfrutar das possibilidades criativas que ela lhe traz.

+ +

Agora é um criativo digital. Desfrute da experiência.

+ +

Sinopse das tecnologias modernas da Web

+ +

Há uma série de tecnologias a aprender se quiser ser um programador da web de front-end. Nesta secção iremos descrevê-las brevemente. Para uma explicação mais detalhada de como algumas delas funcionam em conjunto, leia o nosso artigo Como funciona a web.

+ + + +

É provável que esteja a ler estas palavras dentro de um navegador neste preciso momento (a menos que o tenha imprimido, ou que esteja a utilizar tecnologia de assistência, tal como um leitor de ecrã para o ler). Os navegadores são os programas de software que as pessoas utilizam para consumir a web, e incluem o Firefox, Chrome, Opera, Safari, e Edge.

+ +

HTTP

+ +

Hypertext Transfer Protocol, ou HTTP, é um protocolo de transmissão de mensagens que permite aos navegadores Web comunicarem com servidores (onde os websites são armazenados). Uma conversa típica é algo como

+ +
"Hello web server. Can you give me the files I need to render bbc.co.uk"?
+
+"Sure thing web browser — here you go"
+
+[Downloads files and renders web page]
+ +

A sintaxe das mensagens HTTP (chamadas pedidos e respostas) não é tão legível para o ser humano, mas isto dá-lhe a ideia básica.

+ +

HTML, CSS, e JavaScript

+ +

HTML, CSS, e JavaScript são as três tecnologias principais que irá usar para construir um site:

+ + + +

Tooling

+ +

Uma vez aprendidas as tecnologias de base que podem ser usadas para construir páginas web (como HTML, CSS, e JavaScript), em breve começará a deparar-se com várias ferramentas que podem ser usadas para tornar o seu trabalho mais fácil ou mais eficiente. Os exemplos incluem:

+ + + +

Linguagens de lado de servidor e frameworks

+ +

HTML, CSS, e JavaScript são linguagens de front-end (ou client-side), que significa que eles são processados pelo navegador para produzir a interface dum website que os seus utilizadores possam usar.

+ +

Há outra classe de línguas chamada de back-end (ou línguas do lado do servidor), o que significa que são executadas no servidor antes de o resultado ser então enviado para o navegador para ser exibido. Uma utilização típica para uma linguagem do lado do servidor é obter alguns dados de uma base de dados e gerar algum HTML para conter os dados, antes de depois enviar o HTML para o navegador para o exibir ao utilizador.

+ +

Exemplos de linguagens de lado de servidor incluem C#, Python, PHP e Java.

+ +

As melhores práticas da Web

+ +

Falámos brevemente sobre as tecnologias que irá utilizar para construir sítios web. Agora vamos discutir as melhores práticas que deverá empregar para se certificar de que está a utilizar essas tecnologias o melhor possível.

+ +

Ao fazer desenvolvimento web, a principal causa de incerteza advém do facto de não se saber que combinação de tecnologia cada utilizador utilizará para visualizar o seu site:

+ + + +

Como não sabe exatamente o que os seus utilizadores irão usar, precisa de planear defensivamente - tornar o seu site tão flexível quanto possível, para que todos os utilizadores acima mencionados possam fazer uso dele, mesmo que nem todos possam ter a mesma experiência. Em resumo, estamos a tentar fazer com que a web funcione para todos, tanto quanto possível.

+ +

Encontrará os conceitos abaixo em algum momento dos seus estudos.

+ + + +

Ver também

+ + + + diff --git a/files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html b/files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html new file mode 100644 index 0000000000..a5eacc3afa --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html @@ -0,0 +1,112 @@ +--- +title: Qual será a aparência do seu site da Web? +slug: Learn/Comecar_com_a_Web/Apresentacao_do_meu_site +tags: + - Aprender + - Beginner + - Conteúdo + - Design + - Planear + - Tipos de Letra + - 'l10n:priority' +translation_of: Learn/Getting_started_with_the_web/What_will_your_website_look_like +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Installing_basic_software", "Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web")}}
+ +
+

Este artigo descreve o planeamento e conceptualização necessários antes de escrever o código do site da internet, incluindo "Que informação é que o meu site oferece?", "Quais os tipos de letra e cores que eu quero?" e ​​"O que é que o meu site faz?"

+
+ +

Antes de tudo: planeamento

+ +

Antes de fazer o que quer que seja, precisa de algumas ideias. O que é que o seu site realmente deve fazer? Um site pode fazer qualquer coisa, mas para a sua primeira tentativa, procure manter as coisas simples. Vamos começar a criar uma página web simples com um cabeçalho, uma imagem e alguns parágrafos.

+ +

Para começar, irá precisar de responder a estas questões:

+ +
    +
  1. De que se trata o seu site da Web? Gosta de cães, Nova Iorque, ou Pac-Man?
  2. +
  3. Que informação é que vai apresentar acerca o assunto? Escreva um título e alguns parágrafos, e pense numa imagem que gostaria de mostrar na sua página.
  4. +
  5. Como será apresentado o seu site da Web, em termos simples de alto nível? Qual é a cor de fundo? Que tipo de letra é apropriado: formal, desenhos, negrito e tom alto, subtil?
  6. +
+ +
+

Nota: Projetos complexos precisam de diretrizes detalhadas que abordem todos os detalhes de cores, tipos de letra, espaçamento entre elementos de uma página, estilo de escrita apropriado, e assim por diante. Isto às vezes é chamado guia de desenho ou livro de marca, e pode ver um exemplo em  Firefox OS - Orientações (inglês).

+
+ +

Esboçar o seu desenho

+ +

A seguir, pegue numa caneta e papel e crie um esboço do layout do seu site. Para a sua primeira página, não há muito o que esboçar, mas deve adquirir o hábito de fazer isso agora. Isto é mesmo uma grande ajuda — não tem que ser um Van Gogh!

+ +

+ +
+

Nota: Mesmo em sites a sérios, complexos, a equipa de design costuma começar com esboços grosseiros em papel e mais tarde constrói maquetas digitais com um editor de imagem ou tecnologias web.

+ +

Equipas de desenvolvimento web geralmente incluem um designer gráfico e um designer {{Glossary("UX", "user-experience")}} (UX). Obviamente, os designers gráficos montam os elementos visuais do site. Designers UX têm um papel mais abstrato, que consiste em abordar a forma como utilizadores vão experimentar e interagir com o site.

+
+ +

Escolha do conteúdo

+ +

Nesta altura, é boa ideia começar a criar o conteúdo que virá a aparecer na sua página da internet.

+ +

Texto

+ +

Ainda deve ter o parágrafo e títulos de há bocado. Mantenha-os por perto.

+ +

Cor do tema

+ +

Para escolher uma cor, vá ao Seletor de Cores e encontre uma cor de que gosta. Quando clicar numa cor, vai ver um código estranho com seis caracteres, tal como #660066. Este é um código hexadecimal que representa um tom de cor específico. Aponte o código num local de fácil acesso.

+ +

+ +

Imagens

+ +

Para escolher uma imagem, pesquise Images no Google procure algo adequado.

+ +
    +
  1. Quando encontrar a imagem que quer, clique nela.
  2. +
  3. Prima o botão Ver imagem.
  4. +
  5. Na página seguinte, carregue o botão direito do rato (Ctrl + clique nos Mac), escolha Guardar imagem como..., e escolha um lugar seguro para guardar a imagem. Em alternativa, copie o endereço da imagem da barra de endereço do seu navegador para a utilizar mais tarde.
  6. +
+ +

+ +

+ +
+

Nota: A maioria das imagens, incluindo na pesquisa de Imagens do Google, estão protegidas por direitos de autor. Para reduzir probabilidades de violar estes direitos, pode usar o filtro de licença do  Google. Primeiro, clique em Ferramentas de Pesquisa, e depois em Direitos de utilização:

+ +

+
+ +

Tipo de letra

+ +

Para escolher um tipo de letra:

+ +
    +
  1. Vá ao Google Fonts e deslize para baixo até encontrar um de que goste. Também pode usar os controlos à direita para filtrar resultados.
  2. +
  3. Clique no ícone "mais" (Adicionar) perto do tipo de letra que escolheu.
  4. +
  5. Clique no botão "* Family Selected" no painel no fim da página ("*" será o número de tipos de letra selecionados).
  6. +
  7. Na caixa apresentada, copie as linhas de código que o Google lhe dará para um editor de texto e guarde para utilizar mais tarde.
  8. +
+ +

+ +

+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Installing_basic_software", "Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web")}}
+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/html/como/adicionar_um_mapa_de_zona_clicavel_numa_imagem/index.html b/files/pt-pt/learn/html/como/adicionar_um_mapa_de_zona_clicavel_numa_imagem/index.html deleted file mode 100644 index d70dd147fc..0000000000 --- a/files/pt-pt/learn/html/como/adicionar_um_mapa_de_zona_clicavel_numa_imagem/index.html +++ /dev/null @@ -1,203 +0,0 @@ ---- -title: Adicionar um mapa de zona clicável numa imagem -slug: Learn/HTML/Como/Adicionar_um_mapa_de_zona_clicavel_numa_imagem -translation_of: Learn/HTML/Howto/Add_a_hit_map_on_top_of_an_image ---- -
-

Aqui, nós explicamos como configurar um mapa de imagens, e algumas desvantagens para considerar primeiro.

-
- - - - - - - - - - - - -
Pré-requisitos:Já deverá saber como criar um documento HTML básico e como adicionar imagens acessíveis para uma página da Web.
Objetivo:Learn how to make different regions of one image link to different pages.
- -
-

This article discusses client-side image maps only. Do not use server-side image maps, which require the user to have a mouse.

-
- -

Mapas de imagens, e as suas desvantagens

- -

When you nest an image inside {{htmlelement('a')}}, the entire image links to one webpage. An image map, on the other hand, contains several active regions (called "hotspots") that each link to a different resource.

- -

Formerly, image maps were a popular navigation device, but it’s important to thoroughly consider their performance and accessibility ramifications.

- -

Text links (perhaps styled with CSS) are preferable to image maps for several reasons: text links are lightweight, maintainable, often more SEO-friendly, and support accessibility needs (e.g., screen readers, text-only browsers, translation services).

- -

Como inserir uma imagem de mapa, devidamente

- -

Passo 1: A imagem

- -

Nem qualquer imagem é aceitável.

- - - -

You insert your image much the same way as always (with an {{htmlelement("img")}} element and {{htmlattrxref("alt",'img')}} text). If the image is only present as a navigation device, you may write alt="", provided you furnish appropriate {{htmlattrxref("alt",'area')}} text in the {{htmlelement('area')}} elements later on.

- -

You will need a special {{htmlattrxref("usemap","img")}} attribute. Come up with a unique name, containing no spaces, for your image map. Then assign that name (preceded by a hash) as the value for the usemap attribute:

- -
<img
-  src="image-map.png"
-  alt=""
-  usemap="#example-map-1" />
- -

Passo 2: Ativar os seus pontos de hotspots

- -

In this step, put all your code inside a {{htmlelement('map')}} element. <map> only needs one attribute, the same map {{htmlattrxref("name","map")}} as you used in your usemap attribute above:

- -
<map name="example-map-1">
-
-</map>
- -

Inside the <map> element, we need {{htmlelement('area')}} elements. An <area> element corresponds to a single hotspot. To keep keyboard navigation intuitive, make sure the source order of <area> elements corresponds to the visual order of hotspots.

- -

<area> elements are empty elements, but do require four attributes:

- -
-
{{htmlattrxref('shape','area')}}
-
{{htmlattrxref('coords','area')}}
-
-

shape takes one of four values: circle, rect, poly, and default. (A default <area> occupies the entire image, minus any other hotspots you’ve defined.) The shape you choose determines the coordinate information you’ll need to provide in coords.

- -
    -
  • For a circle, provide the center's x and y coordinates, followed by the length of the radius.
  • -
  • For a rectangle, provide the x/y coordinates of the upper-left and bottom-right corners.
  • -
  • For a polygon, to provide the x/y coordinates of each corner (so, at least six values).
  • -
- -

Coordinates are given in CSS pixels.

- -

In case of overlap, source order carries the day.

-
-
{{htmlattrxref('href','area')}}
-
The URL of the resource you’re linking to. You may leave this attribute blank if you don’t want the current area to link anywhere (say, if you’re making a hollow circle.)
-
{{htmlattrxref('alt','area')}}
-
-

A mandatory attribute, telling people where the link goes or what it does. alt text only displays when the image is unavailable. Please refer to our guidelines for writing accessible link text.

- -

You may write alt="" if the href attribute is blank and the entire image already has an alt attribute.

-
-
- -
<map name="example-map-1">
-  <area shape="circle" coords="200,250,25"
-    href="page-2.html" alt="circle example" />
-
-
-  <area shape="rect" coords="10, 5, 20, 15"
-    href="page-3.html" alt="rectangle example" />
-
-</map>
- -

Passo 3: Certificar-se de que este funciona para toda a gente

- -

You aren’t done until you test image maps rigorously on many browsers and devices. Try following links with your keyboard alone. Try turning images off.

- -

If your image map is wider than about 240px, you’ll need to make further adjustments to make your website responsive. It's not enough to resize the image for small screens, because the coordinates stay the same and no longer match the image.

- -

If you must use image maps, you may want to look into Matt Stow's jQuery plugin. Alternatively, Dudley Storey demonstrates a way to use SVG for an image map effect, along with a subsequent combined SVG-raster hack for bitmap images.

- -

Saiba mais

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/html/como/index.html b/files/pt-pt/learn/html/como/index.html deleted file mode 100644 index abbfb425f3..0000000000 --- a/files/pt-pt/learn/html/como/index.html +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: Utilizar HTML para resolver problemas comuns -slug: Learn/HTML/Como -tags: - - HTML - - Programação Scripting -translation_of: Learn/HTML/Howto ---- -
{{LearnSidebar}}
- -

As seguintes hiperligações apontam para soluções de problemas comuns diários que terá de resolver com HTML.

- -
-
-

Estrutura básica

- -

The most basic application of HTML is document structure. If you're new to HTML you should start with this.

- - - -

Semântica de nível de texto básica

- -

HTML specializes in providing semantic information for a document, so HTML answers many questions you might have about how to get your message across best in your document.

- - -
- -
-

Hiperligações

- -

One of the main reasons for HTML is make navigation easy with {{Glossary("hyperlink", "hyperlinks")}}, which can be used in many different ways:

- - - -

Imagens e multimédia

- - - -

Scripting e estilização

- -

HTML only sets up document structure. To solve presentation issues, use {{glossary("CSS")}}, or use scripting to make your page interactive.

- - - -

Conteúdo integrado

- - -
-
- -

Problemas incomuns ou avançados

- -

Beyond the basics, HTML is very rich and offers advanced features for solving complex problems. These articles help you tackle the less common use cases you may face:

- -
-
-

Formulários

- -

Forms are a complex HTML structure made to send data from a webpage to a web server. We encourage you to go over our full dedicated guide. Here is where you should start:

- - - -

Informação tabular

- -

Some information, called tabular data, needs to be organized into tables with columns and rows. It's one of the most complex HTML structures, and mastering it is not easy:

- - - -

Representação de dados

- - - -

Interatividade

- - -
- -
-

Semântica de texto avançada

- - - -

Imagens e multimédia avançadas

- - - -

Internacionalização

- -

HTML is not monolingual. It provides tools to handle common internationalization issues.

- - - -

Desempenho

- - -
-
- -

     

diff --git a/files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html b/files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html new file mode 100644 index 0000000000..d70dd147fc --- /dev/null +++ b/files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html @@ -0,0 +1,203 @@ +--- +title: Adicionar um mapa de zona clicável numa imagem +slug: Learn/HTML/Como/Adicionar_um_mapa_de_zona_clicavel_numa_imagem +translation_of: Learn/HTML/Howto/Add_a_hit_map_on_top_of_an_image +--- +
+

Aqui, nós explicamos como configurar um mapa de imagens, e algumas desvantagens para considerar primeiro.

+
+ + + + + + + + + + + + +
Pré-requisitos:Já deverá saber como criar um documento HTML básico e como adicionar imagens acessíveis para uma página da Web.
Objetivo:Learn how to make different regions of one image link to different pages.
+ +
+

This article discusses client-side image maps only. Do not use server-side image maps, which require the user to have a mouse.

+
+ +

Mapas de imagens, e as suas desvantagens

+ +

When you nest an image inside {{htmlelement('a')}}, the entire image links to one webpage. An image map, on the other hand, contains several active regions (called "hotspots") that each link to a different resource.

+ +

Formerly, image maps were a popular navigation device, but it’s important to thoroughly consider their performance and accessibility ramifications.

+ +

Text links (perhaps styled with CSS) are preferable to image maps for several reasons: text links are lightweight, maintainable, often more SEO-friendly, and support accessibility needs (e.g., screen readers, text-only browsers, translation services).

+ +

Como inserir uma imagem de mapa, devidamente

+ +

Passo 1: A imagem

+ +

Nem qualquer imagem é aceitável.

+ + + +

You insert your image much the same way as always (with an {{htmlelement("img")}} element and {{htmlattrxref("alt",'img')}} text). If the image is only present as a navigation device, you may write alt="", provided you furnish appropriate {{htmlattrxref("alt",'area')}} text in the {{htmlelement('area')}} elements later on.

+ +

You will need a special {{htmlattrxref("usemap","img")}} attribute. Come up with a unique name, containing no spaces, for your image map. Then assign that name (preceded by a hash) as the value for the usemap attribute:

+ +
<img
+  src="image-map.png"
+  alt=""
+  usemap="#example-map-1" />
+ +

Passo 2: Ativar os seus pontos de hotspots

+ +

In this step, put all your code inside a {{htmlelement('map')}} element. <map> only needs one attribute, the same map {{htmlattrxref("name","map")}} as you used in your usemap attribute above:

+ +
<map name="example-map-1">
+
+</map>
+ +

Inside the <map> element, we need {{htmlelement('area')}} elements. An <area> element corresponds to a single hotspot. To keep keyboard navigation intuitive, make sure the source order of <area> elements corresponds to the visual order of hotspots.

+ +

<area> elements are empty elements, but do require four attributes:

+ +
+
{{htmlattrxref('shape','area')}}
+
{{htmlattrxref('coords','area')}}
+
+

shape takes one of four values: circle, rect, poly, and default. (A default <area> occupies the entire image, minus any other hotspots you’ve defined.) The shape you choose determines the coordinate information you’ll need to provide in coords.

+ +
    +
  • For a circle, provide the center's x and y coordinates, followed by the length of the radius.
  • +
  • For a rectangle, provide the x/y coordinates of the upper-left and bottom-right corners.
  • +
  • For a polygon, to provide the x/y coordinates of each corner (so, at least six values).
  • +
+ +

Coordinates are given in CSS pixels.

+ +

In case of overlap, source order carries the day.

+
+
{{htmlattrxref('href','area')}}
+
The URL of the resource you’re linking to. You may leave this attribute blank if you don’t want the current area to link anywhere (say, if you’re making a hollow circle.)
+
{{htmlattrxref('alt','area')}}
+
+

A mandatory attribute, telling people where the link goes or what it does. alt text only displays when the image is unavailable. Please refer to our guidelines for writing accessible link text.

+ +

You may write alt="" if the href attribute is blank and the entire image already has an alt attribute.

+
+
+ +
<map name="example-map-1">
+  <area shape="circle" coords="200,250,25"
+    href="page-2.html" alt="circle example" />
+
+
+  <area shape="rect" coords="10, 5, 20, 15"
+    href="page-3.html" alt="rectangle example" />
+
+</map>
+ +

Passo 3: Certificar-se de que este funciona para toda a gente

+ +

You aren’t done until you test image maps rigorously on many browsers and devices. Try following links with your keyboard alone. Try turning images off.

+ +

If your image map is wider than about 240px, you’ll need to make further adjustments to make your website responsive. It's not enough to resize the image for small screens, because the coordinates stay the same and no longer match the image.

+ +

If you must use image maps, you may want to look into Matt Stow's jQuery plugin. Alternatively, Dudley Storey demonstrates a way to use SVG for an image map effect, along with a subsequent combined SVG-raster hack for bitmap images.

+ +

Saiba mais

+ + + +
+ + + + + +
diff --git a/files/pt-pt/learn/html/howto/index.html b/files/pt-pt/learn/html/howto/index.html new file mode 100644 index 0000000000..abbfb425f3 --- /dev/null +++ b/files/pt-pt/learn/html/howto/index.html @@ -0,0 +1,153 @@ +--- +title: Utilizar HTML para resolver problemas comuns +slug: Learn/HTML/Como +tags: + - HTML + - Programação Scripting +translation_of: Learn/HTML/Howto +--- +
{{LearnSidebar}}
+ +

As seguintes hiperligações apontam para soluções de problemas comuns diários que terá de resolver com HTML.

+ +
+
+

Estrutura básica

+ +

The most basic application of HTML is document structure. If you're new to HTML you should start with this.

+ + + +

Semântica de nível de texto básica

+ +

HTML specializes in providing semantic information for a document, so HTML answers many questions you might have about how to get your message across best in your document.

+ + +
+ +
+

Hiperligações

+ +

One of the main reasons for HTML is make navigation easy with {{Glossary("hyperlink", "hyperlinks")}}, which can be used in many different ways:

+ + + +

Imagens e multimédia

+ + + +

Scripting e estilização

+ +

HTML only sets up document structure. To solve presentation issues, use {{glossary("CSS")}}, or use scripting to make your page interactive.

+ + + +

Conteúdo integrado

+ + +
+
+ +

Problemas incomuns ou avançados

+ +

Beyond the basics, HTML is very rich and offers advanced features for solving complex problems. These articles help you tackle the less common use cases you may face:

+ +
+
+

Formulários

+ +

Forms are a complex HTML structure made to send data from a webpage to a web server. We encourage you to go over our full dedicated guide. Here is where you should start:

+ + + +

Informação tabular

+ +

Some information, called tabular data, needs to be organized into tables with columns and rows. It's one of the most complex HTML structures, and mastering it is not easy:

+ + + +

Representação de dados

+ + + +

Interatividade

+ + +
+ +
+

Semântica de texto avançada

+ + + +

Imagens e multimédia avançadas

+ + + +

Internacionalização

+ +

HTML is not monolingual. It provides tools to handle common internationalization issues.

+ + + +

Desempenho

+ + +
+
+ +

     

diff --git a/files/pt-pt/learn/html/introducao_ao_html/criar_hiperligacoes/index.html b/files/pt-pt/learn/html/introducao_ao_html/criar_hiperligacoes/index.html deleted file mode 100644 index 502bfda4cf..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/criar_hiperligacoes/index.html +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: Criar hiperligações -slug: Learn/HTML/Introducao_ao_HTML/Criar_hiperligacoes -tags: - - Aprender - - Guía - - HTML - - HTTP - - Hiperligações - - Principiante - - URL - - título -translation_of: Learn/HTML/Introduction_to_HTML/Creating_hyperlinks ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}
- -

Hyperlinks are really important — they are what makes the Web a web. This article shows the syntax required to make a link, and discusses link best practices.

- - - - - - - - - - - - -
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:To learn how to implement a hyperlink effectively, and link multiple files together.
- - - -

Hyperlinks are one of the most exciting innovations the Web has to offer. Well, they've been a feature of the Web since the very beginning, but they are what makes the Web a Web — they allow us to link our documents to any other document (or other resource) we want to, we can also link to specific parts of documents, and we can make apps available at a simple web address (contrast this to native apps, which have to be installed and all that business.) Just about any web content can be converted to a link, so that when clicked (or otherwise activated) it will make the web browser go to another web address ({{glossary("URL")}}).

- -
-

Note: A URL can point to HTML files, text files, images, text documents, video and audio files, and anything else that can live on the Web. If the web browser doesn't know how to display or handle the file, it will ask you if you want to open the file (in which case the duty of opening or handling the file is passed to a suitable native app on the device) or download the file (in which case you can try to deal with it later on.)

-
- -

The BBC homepage, for example, contains a large number of links that point not only to multiple news stories, but also different areas of the site (navigation functionality), login/registration pages (user tools) and more.

- -

frontpage of bbc.co.uk, showing many news items, and navigation menu functionality

- - - -

A basic link is created by wrapping the text (or other content, see {{anch("Block level links")}}) you want to turn into a link inside an {{htmlelement("a")}} element, and giving it an {{htmlattrxref("href", "a")}} attribute (also known as a Hypertext Reference , or target) that will contain the web address you want the link to point to.

- -
<p>I'm creating a link to
-<a href="https://www.mozilla.org/en-US/">the Mozilla homepage</a>.
-</p>
- -

This gives us the following result:

- -

I'm creating a link to the Mozilla homepage.

- -

Adding supporting information with the title attribute

- -

Another attribute you may want to add to your links is title; this is intended to contain supplementary useful information about the link, such as what kind of information the page contains, or things to be aware of. For example:

- -
<p>I'm creating a link to
-<a href="https://www.mozilla.org/en-US/"
-   title="The best place to find more information about Mozilla's
-          mission and how to contribute">the Mozilla homepage</a>.
-</p>
- -

This gives us the following result (the title will come up as a tooltip when the link is hovered over):

- -

I'm creating a link to the Mozilla homepage.

- -
-

Note: A link title is only revealed on mouse hover, which means that people relying on keyboard controls to navigate web pages will have difficulty accessing title information. If a title's information is truly important to the usability of page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.

-
- - - -

Active learning time: we'd like you to create an HTML document using your local code editor (our getting started template would do just fine.)

- - - - - -

As mentioned before, you can turn just about any content into a link, even block level elements. If you had an image you wanted to turn into a link, you could just put the image between <a></a> tags.

- -
<a href="https://www.mozilla.org/en-US/">
-  <img src="mozilla-image.png" alt="mozilla logo that links to the mozilla homepage">
-</a>
- -
-

Note: You'll find out a lot more about using images on the Web in a future article.

-
- -

A quick primer on URLs and paths

- -

To fully understand link targets, you need to understand URLs and file paths. This section gives you the information you need to achieve this.

- -

A URL, or Uniform Resource Locator is simply a string of text that defines where something is located on the Web. For example Mozilla's English homepage is located at https://www.mozilla.org/en-US/.

- -

URLs use paths to find files. Paths specify where in the filesystem the file you are interested in is located. Let's look at a simple example of a directory structure (see the creating-hyperlinks directory.)

- -

A simple directory structure. The parent directory is called creating-hyperlinks and contains two files called index.html and contacts.html, and two directories called projects and pdfs, which contain an index.html and a project-brief.pdf file, respectively

- -

The root of this directory structure is called creating-hyperlinks. When working locally with a web site, you will have one directory that the whole site goes inside. Inside the root, we have an index.html file and a contacts.html. In a real website, index.html would be our home page or landing page (a web page that serves as the entry point for a website or a particular section of a website.).

- -

There are also two directories inside our root — pdfs and projects. These each have a single file inside them — a PDF (project-brief.pdf) and an index.html file, respectively. Note how you can quite happily have two index.html files in one project as long as they are in different locations in the filesystem. Many web sites do. The second index.html would perhaps be the main landing page for project-related information.

- - - -
-

Note: You can combine multiple instances of these features into complex URLs, if needed, e.g. ../../../complex/path/to/my/file.html.

-
- -

Document fragments

- -

It is possible to link to a specific part of an HTML document (known as a document fragment), rather than just to the top of the document. To do this you first have to assign an {{htmlattrxref("id")}} attribute to the element you want to link to. It normally makes sense to link to a specific heading, so this would look something like the following:

- -
<h2 id="Mailing_address">Mailing address</h2>
- -

Then to link to that specific id, you'd include it at the end of the URL, preceded by a hash/pound symbol, for example:

- -
<p>Want to write us a letter? Use our <a href="contacts.html#Mailing_address">mailing address</a>.</p>
- -

You can even use the document fragment reference on its own to link to another part of the same document:

- -
<p>The <a href="#Mailing_address">company mailing address</a> can be found at the bottom of this page.</p>
- -

Absolute versus relative URLs

- -

Two terms you'll come across on the Web are absolute URL and relative URL:

- -

absolute URL: Points to a location defined by its absolute location on the web, including {{glossary("protocol")}} and {{glossary("domain name")}}. So for example, if an index.html page is uploaded to a directory called projects that sits inside the root of a web server, and the web site's domain is http://www.example.com, the page would be available at http://www.example.com/projects/index.html (or even just http://www.example.com/projects/, as most web servers just look for a landing page such as index.html to load if it is not specified in the URL.)

- -

An absolute URL will always point to the same location, no matter where it is used.

- -

relative URL: Points to a location that is relative to the file you are linking from, more like what we looked at in the previous section. For example, if we wanted to link from our example file at http://www.example.com/projects/index.html to a PDF file in the same directory, the URL would just be the filename — e.g. project-brief.pdf — no extra information needed. If the PDF was available in a subdirectory inside projects called pdfs, the relative link would be pdfs/project-brief.pdf (the equivalent absolute URL would be http://www.example.com/projects/pdfs/project-brief.pdf.)

- -

A relative URL will point to different places depending on where the file it is used inside is located — for example if we moved our index.html file out of the projects directory and into the root of the web site (the top level, not in any directories), the pdfs/project-brief.pdf relative URL link inside it would now point to a file located at http://www.example.com/pdfs/project-brief.pdf, not a file located at http://www.example.com/projects/pdfs/project-brief.pdf.

- -

Of course, the location of the project-brief.pdf file and pdfs folder won't suddenly change because you moved the index.html file — this would make your link point to the wrong place, so it wouldn't work if clicked on. You need to be careful!

- - - -

There are some best practices to follow when writing links. Let's look at these now.

- - - - - -

It's easy to throw links up on your page. That's not enough. We need to make our links accessible to all readers, regardless of their current context and which tools they prefer. For example:

- - - -

Let's look at a specific example:

- -

Good link text: Download Firefox

- -
<p><a href="https://firefox.com/">
-  Download Firefox
-</a></p>
- -

Bad link text: Click here to download Firefox

- -
<p><a href="https://firefox.com/">
-  Click here
-</a>
-to download Firefox</p>
-
- -

Other tips:

- - - - - -

From the description above, you might think that it is a good idea to just use absolute links all the time; after all, they don't break when a page is moved like relative links. However, you should use relative links wherever possible when linking to other locations within the same website (when linking to another website, you will need to use an absolute link):

- - - -

Linking to non-HTML resources — leave clear signposts

- -

When linking to a resource that will be downloaded (like a PDF or Word document) or streamed (like video or audio) or has another potentially unexpected effect (opens a popup window, or loads a Flash movie), you should add clear wording to reduce any confusion. It can be quite annoying for example:

- - - -

Let's look at some examples, to see what kind of text can be used here:

- -
<p><a href="http://www.example.com/large-report.pdf">
-  Download the sales report (PDF, 10MB)
-</a></p>
-
-<p><a href="http://www.example.com/video-stream/" target="_blank">
-  Watch the video (stream opens in separate tab, HD quality)
-</a></p>
-
-<p><a href="http://www.example.com/car-game">
-  Play the car game (requires Flash)
-</a></p>
- -

Use the download attribute when linking to a download

- -

When you are linking to a resource that is to be downloaded rather than opened in the browser, you can use the download attribute to provide a default save filename. Here's an example with a download link to the latest Windows version of Firefox:

- -
<a href="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=en-US"
-   download="firefox-latest-64bit-installer.exe">
-  Download Latest Firefox for Windows (64-bit) (English, US)
-</a>
- -

Active learning: creating a navigation menu

- -

For this exercise, we'd like you to link some pages together with a navigation menu to create a multi-page website. This is one common way in which a website is created — the same page structure is used on every page, including the same navigation menu, so when links are clicked it gives the impression that you are staying in the same place, and different content is being brought up.

- -

You'll need to make local copies of the following four pages, all in the same directory (see also the navigation-menu-start directory for a full file listing):

- - - -

You should:

- -
    -
  1. Add an unordered list in the indicated place on one page, containing the names of the pages to link to. A navigation menu is usually just a list of links, so this is semantically ok.
  2. -
  3. Turn each page name into a link to that page.
  4. -
  5. Copy the navigation menu across to each page.
  6. -
  7. On each page, remove just the link to that same page — it is confusing and pointless for a page to include a link to itself, and the lack of a link acts a good visual reminder of what page you are currently on.
  8. -
- -

The finished example should end up looking something like this:

- -

An example of a simple HTML navigation menu, with home, pictures, projects, and social menu items

- -
-

Note: If you get stuck, or are not sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer.

-
- - - -

It is possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. This is done using the {{HTMLElement("a")}} element and the mailto: URL scheme.

- -

In its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. For example:

- -
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>
-
- -

This results in a link that looks like this: Send email to nowhere.

- -

In fact, the email address is even optional. If you leave it out (that is, your {{htmlattrxref("href", "a")}} is simply "mailto:"), a new outgoing email window will be opened by the user's mail client that has no destination address specified yet. This is often useful as "Share" links that users can click to send an email to an address of their choosing.

- -

Specifying details

- -

In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term.

- -

Here's an example that includes a cc, bcc, subject and body:

- -
<a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email">
-  Send mail with cc, bcc, subject and body
-</a>
- -
-

Note: The values of each field must be URL-encoded, that is with non-printing characters (invisible characters like tabs, carriage returns, and page breaks) and spaces percent-escaped. Also note the use of the question mark (?) to separate the main URL from the field values, and ampersands (&) to separate each field in the mailto: URL. This is standard URL query notation. Read The GET method to understand what URL query notation is more comonly used for.

-
- -

Here are a few other sample mailto URLs:

- - - -

Summary

- -

That's it for links, for now anyway! You'll return to links later on in the course when you start to look at styling them. Next up for HTML, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful — Advanced text formatting is your next stop.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}

- -

In this module

- - diff --git a/files/pt-pt/learn/html/introducao_ao_html/demarcar_uma_carta/index.html b/files/pt-pt/learn/html/introducao_ao_html/demarcar_uma_carta/index.html deleted file mode 100644 index 0545b789e0..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/demarcar_uma_carta/index.html +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Demarcar uma carta -slug: Learn/HTML/Introducao_ao_HTML/demarcar_uma_carta -tags: - - Avaliação - - HTML - - Ligações - - Principiante - - Texto -translation_of: Learn/HTML/Introduction_to_HTML/Marking_up_a_letter ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content", "Learn/HTML/Introduction_to_HTML")}}
- -

We all learn to write a letter sooner or later; it is also a useful example to test out our text formatting skills! In this assessment you'll be given a letter to mark up to test basic and advanced HTML text formatting skills, including hyperlinks, plus we'll test your familiarity with some HTML <head> contents.

- - - - - - - - - - - - -
Prerequisites:Before attempting this assessment you should have already worked through Getting started with HTML, What's in the head? Metadata in HTML, HTML text fundamentals, Creating hyperlinks, and Advanced text formatting.
Objective:To test basic and advanced HTML text formatting and hyperlink skills, and knowledge of what goes in the HTML <head>.
- -

Starting point

- -

To get this assessment started, you should go and grab the raw text you need to mark up, and the CSS you need to include in your HTML. Create a new .html file using your text editor to do your work in (or alternatively use a site like JSBin or Thimble to do your assessment.)

- -

Project brief

- -

For this project, your task is to mark up a letter that needs to be hosted on a university intranet. The letter is a response from a research fellow to a prospective PhD student concerning their application to the university.

- -

Block/structural semantics:

- - - -

Inline semantics:

- - - -

The head of the document:

- - - -

Hints and tips

- - - -

Example

- -

The following screenshot shows an example of what the letter might look like after being marked up.

- -

Example

- -

Assessment

- -

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread about this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introducao_ao_html/depurar_html/index.html b/files/pt-pt/learn/html/introducao_ao_html/depurar_html/index.html deleted file mode 100644 index 9515ff4f37..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/depurar_html/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: Depurar HTML -slug: Learn/HTML/Introducao_ao_HTML/Depurar_HTML -tags: - - Depuração - - Erro - - Guía - - HTML - - Principiante - - Validação -translation_of: Learn/HTML/Introduction_to_HTML/Debugging_HTML ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
- -

Writing HTML is fine, but what if something goes wrong, and you can't work out where the error in the code is? This article will introduce you to some tools that can help you find and fix errors in HTML.

- - - - - - - - - - - - -
Prerequisites:HTML familiarity, as covered in for example Getting started with HTML, HTML text fundamentals, and Creating hyperlinks.
Objective:Learn the basics of using debugging tools to find problems in HTML.
- -

Debugging isn't scary

- -

When writing code of some kind, everything is usually fine, until that dreaded moment when an error occurs — you've done something wrong, so your code doesn't work — either not at all, or not quite how you wanted it to. For example, the following shows an error reported when trying to {{glossary("compile")}} a simple program written in the Rust language.

- -

A console window showing the result of trying to compile a rust program with a missing quote around a string in a print statement. The error message reported is error: unterminated double quote string.Here, the error message is relatively easy to understand — "unterminated double quote string". If you look at the listing, you can probably see how println!(Hello, world!"); might logically be missing a double quote. However, error messages can quickly get more complicated and less easy to interpret as programs get bigger, and even simple cases can look a little intimidating to someone who doesn't know anything about Rust.

- -

Debugging doesn't have to be scary though —  the key to being comfortable with writing and debugging any programming language or code is familiarity with both the language and the tools.

- -

HTML and debugging

- -

HTML is not as complicated to understand as Rust. HTML is not compiled into a different form before the browser parses it and shows the result (it is interpreted, not compiled). And HTML's {{glossary("element")}} syntax is arguably a lot easier to understand than a "real programming language" like Rust, {{glossary("JavaScript")}}, or {{glossary("Python")}}. The way that browsers parse HTML is a lot more permissive than how programming languages are run, which is both a good and a bad thing.

- -

Permissive code

- -

So what do we mean by permissive? Well, generally when you do something wrong in code, there are two main types of error that you'll come across:

- - - -

HTML itself doesn't suffer from syntax errors because browsers parse it permissively, meaning that the page still displays even if there are syntax errors. Browsers have built-in rules to state how to interpret incorrectly written markup, so you'll get something running, even if it is not what you expected. This, of course, can still be a problem!

- -
-

Note: HTML is parsed permissively because when the web was first created, it was decided that allowing people to get their content published was more important than making sure the syntax was absolutely correct. The web would probably not be as popular as it is today, if it had been more strict from the very beginning.

-
- -

Active learning: Studying permissive code

- -

It's time to study the permissive nature of HTML code.

- -
    -
  1. First, download our debug-example demo and save it locally. This demo is deliberately written to have some errors in it for us to explore (the HTML markup is said to be badly-formed, as opposed to well-formed).
  2. -
  3. Next, open it in a browser. You will see something like this:A simple HTML document with a title of HTML debugging examples, and some information about common HTML errors, such as unclosed elements, badly nested elements, and unclosed attributes.
  4. -
  5. This immediately doesn't look great; let's look at the source code to see if we can work out why (only the body contents are shown): -
    <h1>HTML debugging examples</h1>
    -
    -<p>What causes errors in HTML?
    -
    -<ul>
    -  <li>Unclosed elements: If an element is <strong>not closed properly,
    -      then its effect can spread to areas you didn't intend
    -
    -  <li>Badly nested elements: Nesting elements properly is also very important
    -      for code behaving correctly. <strong>strong <em>strong emphasised?</strong>
    -      what is this?</em>
    -
    -  <li>Unclosed attributes: Another common source of HTML problems. Let's
    -      look at an example: <a href="https://www.mozilla.org/>link to Mozilla
    -      homepage</a>
    -</ul>
    -
  6. -
  7. Let's review the problems: -
      -
    • The {{htmlelement("p","paragraph")}} and {{htmlelement("li","list item")}} elements have no closing tags. Looking at the image above, this doesn't seem to have affected the markup rendering too badly, as it is easy to infer where one element should end and another should begin.
    • -
    • The first {{htmlelement("strong")}} element has no closing tag. This is a bit more problematic, as it isn't easy to tell where the element is supposed to end. In fact, the whole of the rest of the text has been strongly emphasised.
    • -
    • This section is badly nested: <strong>strong <em>strong emphasised?</strong> what is this?</em>. It is not easy to tell how this has been interpreted because of the previous problem.
    • -
    • The {{htmlattrxref("href","a")}} attribute value has a missing closing double quote. This seems to have caused the biggest problem — the link has not rendered at all.
    • -
    -
  8. -
  9. Now let's look at the markup the browser has rendered, as opposed to the markup in the source code. To do this, we can use the browser developer tools. If you are not familiar with how to use your browser's developer tools, take a few minutes to review Discover browser developer tools.
  10. -
  11. In the DOM inspector, you can see what the rendered markup looks like: The HTML inspector in Firefox, with our example's paragraph highlighted, showing the text "What causes errors in HTML?" Here you can see that the paragraph element has been closed by the browser.
  12. -
  13. Using the DOM inspector, let's explore our code in detail to see how the browser has tried to fix our HTML errors (we did the review in Firefox; other modern browsers should give the same result): -
      -
    • The paragraphs and list items have been given closing tags.
    • -
    • It isn't clear where the first <strong> element should be closed, so the browser has wrapped each separate block of text with its own strong tag, right down to the bottom of the document!
    • -
    • The  incorrect nesting has been fixed by the browser like this: -
      <strong>strong
      -  <em>strong emphasised?</em>
      -</strong>
      -<em> what is this?</em>
      -
    • -
    • The link with the missing double quote has been deleted altogether. The last list item looks like this: -
      <li>
      -  <strong>Unclosed attributes: Another common source of HTML problems.
      -  Let's look at an example: </strong>
      -</li>
      -
    • -
    -
  14. -
- -

HTML validation

- -

So you can see from the above example that you really want to make sure your HTML is well-formed! But how? In a small example like the one seen above, it is easy to search through the lines and find the errors, but what about a huge, complex HTML document?

- -

The best strategy is to start by running your HTML page through the Markup Validation Service — created and maintained by the W3C, the organization that looks after the specifications that define HTML, CSS, and other web technologies. This webpage takes an HTML document as an input, goes through it, and gives you a report to tell you what is wrong with your HTML.

- -

The HTML validator homepage

- -

To specify the HTML to validate, you can give it a web address, upload an HTML file, or directly input some HTML code.

- -

Active learning: Validating an HTML document

- -

Let's try this with our sample document.

- -
    -
  1. First, load up the Markup Validation Service in one browser tab, if it isn't already.
  2. -
  3. Switch to the Validate by Direct Input tab.
  4. -
  5. Copy all the sample document's code (not just the body) and paste it into the large text area shown in the Markup Validation Service.
  6. -
  7. Press the Check button.
  8. -
- -

This should give you a list of errors and other information.

- -

A list of of HTML validation results from the W3C markup validation service

- -

Interpreting the error messages

- -

The error messages are usually helpful, but sometimes they are not so helpful; with a bit of practice you can work out how to interpret these to fix your code. Let's go through the error messages and what they mean. You'll see that each message comes with a line and column number to help you to locate the error easily.

- - - -

If you can't work out what every error message means, don't worry about it — a good idea is to try fixing a few errors at a time. Then try revalidating your HTML to show what errors are left. Sometimes fixing an earlier error will also get rid of other error messages — several errors can often be caused by a single problem, in a domino effect.

- -

You will know when all your errors are fixed when you see the following banner in your output:

- -

Banner that reads "The document validates according to the specified schema(s) and to additional constraints checked by the validator."

- -

Summary

- -

So there we have it, an introduction to debugging HTML, which should give you some useful skills to count on when you start to debug CSS, JavaScript, and other types of code later on in your career. This also marks the end of the Introduction to HTML module learning articles — now you can go on to testing yourself with our assessments: the first one is linked below.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introducao_ao_html/estrutura_documento_website/index.html b/files/pt-pt/learn/html/introducao_ao_html/estrutura_documento_website/index.html deleted file mode 100644 index 059f26a497..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/estrutura_documento_website/index.html +++ /dev/null @@ -1,292 +0,0 @@ ---- -title: "Estrutura do\_documento e do website" -slug: Learn/HTML/Introducao_ao_HTML/Estrutura_documento_website -tags: - - Guía - - HTML - - Layout - - Principiante - - pagina - - semántica -translation_of: Learn/HTML/Introduction_to_HTML/Document_and_website_structure ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}
- -

In addition to defining individual parts of your page (such as "a paragraph" or "an image"), {{glossary("HTML")}} also boasts a number of block level elements used to define areas of your website (such as "the header", "the navigation menu", "the main content column"). This article looks into how to plan a basic website structure, and write the HTML to represent this structure.

- - - - - - - - - - - - -
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals. How hyperlinks work, as covered in Creating hyperlinks.
Objective:Learn how to structure your document using semantic tags, and how to work out the structure of a simple website.
- -

Basic sections of a document

- -

Webpages can and will look pretty different from one another, but they all tend to share similar standard components, unless the page is displaying a fullscreen video or game, is part of some kind of art project, or is just badly structured:

- -
-
header
-
Usually a big strip across the top with a big heading and/or logo. This is where the main common information about a website usually stays from one webpage to another.
-
navigation bar
-
Links to the site's main sections; usually represented by menu buttons, links, or tabs. Like the header, this content usually remains consistent from one webpage to another — having an inconsistent navigation on your website will just lead to confused, frustrated users. Many web designers consider the navigation bar to be part of the header rather than a individual component, but that's not a requirement; in fact some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate.
-
main content
-
A big area in the center that contains most of the unique content of a given webpage, for example the video you want to watch, or the main story you're reading, or the map you want to view, or the news headlines, etc. This is the one part of the website that definitely will vary from page to page!
-
sidebar
-
Some peripheral info, links, quotes, ads, etc. Usually this is contextual to what is contained in the main content (for example on a news article page, the sidebar might contain the author's bio, or links to related articles) but there are also cases where you'll find some recurring elements like a secondary navigation system.
-
footer
-
A strip across the bottom of the page that generally contains fine print, copyright notices, or contact info. It's a place to put common information (like the header) but usually that information is not critical or secondary to the website itself. The footer is also sometimes used for {{Glossary("SEO")}} purposes, by providing links for quick access to popular content.
-
- -

A "typical website" could be laid out something like this:

- -

a simple website structure example featuring a main heading, navigation menu, main content, side bar, and footer.

- -

HTML for structuring content

- -

The simple example shown above isn't pretty, but it is perfectly ok for illustrating a typical website layout example. Some websites have more columns, some are way more complex, but you get the idea. With the right CSS, you could use pretty much any elements to wrap around the different sections and get it looking how you wanted, but as discussed before, we need to respect semantics, and use the right element for the right job.

- -

This is because visuals don't tell the whole story. We use color and font size to draw sighted users' attention to the most useful parts of the content, like the navigation menu and related links, but what about visually impaired people for example, who might not find concepts like "pink" and "large font" very useful?

- -
-

Note: Colorblind people represent around 4% of the world population or, to put it another way, approximately 1 in every 12 men and 1 in every 200 women are colorblind. Blind and visually impaired people represent roughly 4-5% of the world population (in 2012 there were 285 million such people in the world, while the total population was around 7 billion).

-
- -

In your HTML code, you can mark up sections of content based on their functionality — you can use elements that represent the sections of content described above unambiguously, and assistive technologies like screenreaders can recognise those elements and help with tasks like "find the main navigation", or "find the main content." As we mentioned earlier in the course, there are a number of consequences of not using the right element structure and semantics for the right job.

- -

To implement such semantic mark up, HTML provides dedicated tags that you can use to represent such sections, for example:

- - - -

Active learning: exploring the code for our example

- -

Our example seen above is represented by the following code (you can also find the example in our GitHub repository). We'd like you to look at the example above, and then look over the listing below to see what parts make up what section of the visual.

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-
-    <title>My page title</title>
-    <link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Sonsie+One" rel="stylesheet" type="text/css">
-    <link rel="stylesheet" href="style.css">
-
-    <!-- the below three lines are a fix to get HTML5 semantic elements working in old versions of Internet Explorer-->
-    <!--[if lt IE 9]>
-      <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
-    <![endif]-->
-  </head>
-
-  <body>
-    <!-- Here is our main header that is used across all the pages of our website -->
-
-    <header>
-      <h1>Header</h1>
-    </header>
-
-    <nav>
-      <ul>
-        <li><a href="#">Home</a></li>
-        <li><a href="#">Our team</a></li>
-        <li><a href="#">Projects</a></li>
-        <li><a href="#">Contact</a></li>
-      </ul>
-
-       <!-- A Search form is another commmon non-linear way to navigate through a website. -->
-
-       <form>
-         <input type="search" name="q" placeholder="Search query">
-         <input type="submit" value="Go!">
-       </form>
-     </nav>
-
-    <!-- Here is our page's main content -->
-    <main>
-
-      <!-- It contains an article -->
-      <article>
-        <h2>Article heading</h2>
-
-        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Donec a diam lectus. Set sit amet ipsum mauris. Maecenas congue ligula as quam viverra nec consectetur ant hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur.</p>
-
-        <h3>Subsection</h3>
-
-        <p>Donec ut librero sed accu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor.</p>
-
-        <p>Pelientesque auctor nisi id magna consequat sagittis. Curabitur dapibus, enim sit amet elit pharetra tincidunt feugiat nist imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros.</p>
-
-        <h3>Another subsection</h3>
-
-        <p>Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum soclis natoque penatibus et manis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p>
-
-        <p>Vivamus fermentum semper porta. Nunc diam velit, adipscing ut tristique vitae sagittis vel odio. Maecenas convallis ullamcorper ultricied. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, is fringille sem nunc vet mi.</p>
-      </article>
-
-      <!-- the aside content can also be nested within the main content -->
-      <aside>
-        <h2>Related</h2>
-
-        <ul>
-          <li><a href="#">Oh I do like to be beside the seaside</a></li>
-          <li><a href="#">Oh I do like to be beside the sea</a></li>
-          <li><a href="#">Although in the North of England</a></li>
-          <li><a href="#">It never stops raining</a></li>
-          <li><a href="#">Oh well...</a></li>
-        </ul>
-      </aside>
-
-    </main>
-
-    <!-- And here is our main footer that is used across all the pages of our website -->
-
-    <footer>
-      <p>©Copyright 2050 by nobody. All rights reversed.</p>
-    </footer>
-
-  </body>
-</html>
- -

Take some time to look over the code and understand it — the comments inside the code should also help you to understand it. We aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound HTML structure, and then laying it out with CSS. We'll wait for this until you start to study CSS layout as part of the CSS topic.

- -

HTML layout elements in more detail

- -

It's good to understand the overall meaning of all the HTML sectioning elements in detail — this is something you'll work on gradually as you start to get more experience with web development. You can find a lot of detail by reading our HTML element reference. For now, these are the main definitions that you should try to understand:

- - - -

Non-semantic wrappers

- -

Sometimes you'll come across a situation where you can't find an ideal semantic element to group some items together or wrap some content. Sometimes you might want to just group a set of elements together to affect them all as a single entity with some {{glossary("CSS")}} or {{glossary("JavaScript")}}. For cases like these, HTML provides the {{HTMLElement("div")}} and {{HTMLElement("span")}} elements. You should use these preferably with a suitable {{htmlattrxref('class')}} attribute, to provide some kind of label for them so they can be easily targeted.

- -

{{HTMLElement("span")}} is an inline non-semantic element, which you should only use if you can't think of a better semantic text element to wrap your content, or don't want to add any specific meaning. For example:

- -
<p>The King walked drunkenly back to his room at 01:00, the beer doing nothing to aid
-him as he staggered through the door <span class="editor-note">[Editor's note: At this point in the
-play, the lights should be down low]</span>.</p>
- -

In this case, the editor's note is supposed to merely provide extra direction for the director of the play; it is not supposed to have extra semantic meaning. For sighted users, CSS would perhaps be used to distance the note slightly from the main text.

- -

{{HTMLElement("div")}} is a block level non-semantic element, which you should only use if you can't think of a better semantic block element to use, or don't want to add any specific meaning. For example, imagine a shopping cart widget that you could choose to pull up at any point during your time on an e-commerce site:

- -
<div class="shopping-cart">
-  <h2>Shopping cart</h2>
-  <ul>
-    <li>
-      <p><a href=""><strong>Silver earrings</strong></a>: $99.95.</p>
-      <img src="../products/3333-0985/thumb.png" alt="Silver earrings">
-    </li>
-    <li>
-      ...
-    </li>
-  </ul>
-  <p>Total cost: $237.89</p>
-</div>
- -

This isn't really an <aside>, as it doesn't necessarily relate to the main content of the page (you want it viewable from anywhere). It doesn't even particularly warrant using a  <section>, as it isn't part of the main content of the page. So a <div> is fine in this case. We've included a heading as a signpost to aid screenreader users in finding it.

- -
-

Warning: Divs are so convenient to use that it's easy to use them too much. As they carry no semantic value, they just clutter your HTML code. Take care to use them only when there is no better semantic solution and try to reduce their usage to the minimum otherwise you'll have a hard time updating and maintaining your documents.

-
- -

Line breaks and horizontal rules

- -

Two elements that you'll use occasionally and will want to know about are {{htmlelement("br")}} and {{htmlelement("hr")}}:

- -

<br> creates a line break in a paragraph; it is the only way to force a rigid structure in a situation where you want a series of fixed short lines, such as in a postal address or a poem. For example:

- -
<p>There once was a man named O'Dell<br>
-Who loved to write HTML<br>
-But his structure was bad, his semantics were sad<br>
-and his markup didn't read very well.</p>
- -

Without the <br> elements, the paragraph would just be rendered in one long line (as we said earlier in the course, HTML ignores most whitespace); with them in the code, the markup renders like this:

- -

There once was a man named O'Dell
- Who loved to write HTML
- But his structure was bad, his semantics were sad
- and his markup didn't read very well.

- -

<hr> elements create a horizontal rule in the document that denotes a thematic change in the text (such as a change in topic or scene). Visually it just looks like a horizontal line. As an example:

- -
<p>Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.</p>
-<hr>
-<p>Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.</p>
- -

Would render like this:

- -

Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.

- -
-

Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.

- -

Planning a simple website

- -

Once you've planned out the content of a simple webpage, the next logical step is to try to work out what content you want to put on a whole website, what pages you need, and how they should be arranged and link to one another for the best possible user experience. This is called {{glossary("Information architecture")}}. In a large, complex website, a lot of planning can go into this process, but for a simple website of a few pages this can be fairly simple, and fun!

- -
    -
  1. Bear in mind that you'll have a few elements common to most (if not all) pages — such as the navigation menu, and the footer content. If your site is for a business, for example, it's a good idea to have your contact information available in the footer on each page. Note down what you want to have common to every page.the common features of the travel site to go on every page: title and logo, contact, copyright, terms and conditions, language chooser, accessibility policy
  2. -
  3. Next, draw a rough sketch of what you might want the structure of each page to look like (it might look like our simple website above). Note what each block is going to be.A simple diagram of a sample site structure, with a header, main content area, two optional sidebars, and footer
  4. -
  5. Now, brainstorm all the other (not common to every page) content you want to have on your website — write a big list down.A long list of all the features that we could put on our travel site, from searching, to special offers and country-specific info
  6. -
  7. Next, try to sort all these content items into groups, to give you an idea of what parts might live together on different pages. This is very similar to a technique called {{glossary("Card sorting")}}.The items that should appear on a holiday site sorted into 5 categories: Search, Specials, Country-specific info, Search results, and Buy things
  8. -
  9. Now try to sketch a rough sitemap — have a bubble for each page on your site, and draw lines to show the typical workflow between pages. The homepage will probably be in the center, and link to most if not all of the others; most of the pages in a small site should be available from the main navigation, although there are exceptions. You might also want to include notes about how things might be presented.A map of the site showing the homepage, country page, search results, specials page, checkout, and buy page
  10. -
- -

Active learning: create your own sitemap

- -

Try carrying out the above exercise for a website of your own creation. What would you like to make a site about?

- -
-

Note: Save your work somewhere; you might need it later on.

-
- -

Summary

- -

At this point you should have a better idea about how to structure a web page/site. In the last article of this module, we'll study how to debug HTML.

- -

See also

- - - -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introducao_ao_html/estruturar_pagina_de_conteudo/index.html b/files/pt-pt/learn/html/introducao_ao_html/estruturar_pagina_de_conteudo/index.html deleted file mode 100644 index 1f6310a395..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/estruturar_pagina_de_conteudo/index.html +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: Estruturar uma página de conteúdo -slug: Learn/HTML/Introducao_ao_HTML/Estruturar_pagina_de_conteudo -tags: - - Avaliação - - Estrutura - - HTML - - Principiante - - semántica -translation_of: Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
- -

Structuring a page of content ready for laying it out using CSS is a very important skill to master, so in this assessment you'll be tested on your ability to think about how a page might end up looking, and choose appropriate structural semantics to build a layout on top of.

- - - - - - - - - - - - -
Prerequisites:Before attempting this assessment you should have already worked through the rest of the course, with a particular emphasis on Document and website structure.
Objective:To test knowledge of web page structures, and how to represent a prospective layout design in markup.
- -

Starting point

- -

To get this assessment started, you should go and grab the zip file containing all the starting assets. The zip file contains:

- - - -

Create the example on your local computer, or alternatively use a site like JSBin or Thimble to do your assessment.

- -

Project brief

- -

For this project, your task is to take the content for the homepage of a bird watching website and add structural elements to it so it can have a page layout applied to it. It needs to have:

- - - -

You need to add a suitable wrapper for:

- - - -

You should also:

- - - -

Hints and tips

- - - -

Example

- -

The following screenshot shows an example of what the homepage might look like after being marked up.

- -

The finished example for the assessment; a simple webpage about birdwatching, including a heading of "Birdwatching", bird photos, and a welcome message

- -

Assessment

- -

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread about this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

- -

{{PreviousMenu("Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introducao_ao_html/formatacao_avancada_texto/index.html b/files/pt-pt/learn/html/introducao_ao_html/formatacao_avancada_texto/index.html deleted file mode 100644 index 882f2eec7b..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/formatacao_avancada_texto/index.html +++ /dev/null @@ -1,691 +0,0 @@ ---- -title: Formatação avançada de texto -slug: Learn/HTML/Introducao_ao_HTML/Formatacao_avancada_texto -tags: - - Aprender - - Guía - - HTML - - Principiante - - Texto - - abreviatura - - semántica -translation_of: Learn/HTML/Introduction_to_HTML/Advanced_text_formatting ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}
- -

There are many other elements in HTML for formatting text, which we didn't get to in the HTML text fundamentals article. The elements described in this article are less known, but still useful to know about (and this is still not a complete list by any means). Here you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more.

- - - - - - - - - - - - -
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:To learn how to use lesser-known HTML elements to mark up advanced semantic features.
- -

Description lists

- -

In HTML text fundamentals, we walked through how to mark up basic lists in HTML, but we didn't mention the third type of list you'll occasionally come across — description lists. The purpose of these lists is to mark up a set of items and their associated descriptions, such as terms and definitions, or questions and answers. Let's look at an example of a set of terms and definitions:

- -
soliloquy
-In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
-monologue
-In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
-aside
-In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information
- -

Description lists use a different wrapper than the other list types — {{htmlelement("dl")}}; in addition each term is wrapped in a {{htmlelement("dt")}} (description term) element, and each description is wrapped in a {{htmlelement("dd")}} (description definition) element. Let's finish marking up our example:

- -
<dl>
-  <dt>soliloquy</dt>
-  <dd>In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)</dd>
-  <dt>monologue</dt>
-  <dd>In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.</dd>
-  <dt>aside</dt>
-  <dd>In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought, or piece of additional background information.</dd>
-</dl>
- -

The browser default styles will display description lists with the descriptions indented somewhat from the terms. MDN's styles follow this convention fairly closely, but also embolden the terms for extra definition.

- -
-
soliloquy
-
In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
-
monologue
-
In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
-
aside
-
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.
-
- -

Note that it is permitted to have a single term with multiple descriptions, for example:

- -
-
aside
-
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.
-
In writing, a section of content that is related to the current topic, but doesn't fit directly into the main flow of content so is presented nearby (often in a box off to the side.)
-
- -

Active learning: Marking up a set of definitions

- -

It's time to try your hand at description lists; add elements to the raw text in the Input field so that it appears as a description list in the Output field. You could try using your own terms and descriptions if you like.

- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code', 700, 350, "", "", "hide-codepen-jsfiddle") }}

- -

Quotations

- -

HTML also has features available for marking up quotations; which element you use depends on whether you are marking up a block or inline quotation.

- -

Blockquotes

- -

If a section of block level content (be it a paragraph, multiple paragraphs, a list, etc.) is quoted from somewhere else, you should wrap it inside a {{htmlelement("blockquote")}} element to signify this, and include a URL pointing to the source of the quote inside a {{htmlattrxref("cite","blockquote")}} attribute. For example, the following markup is taken from the MDN <blockquote> element page:

- -
<p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
-Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
- -

To turn this into a block quote, we would just do this:

- -
<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
-  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
-  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
-</blockquote>
- -

Browser default styling will render this as an indented paragraph, as an indicator that it is a quote; MDN does this, but also adds some extra styling:

- -
-

The HTML <blockquote> Element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation.

-
- -

Inline quotations

- -

Inline quotations work in exactly the same way, except that they use the {{htmlelement("q")}} element. For example, the below bit of markup contains a quotation from the MDN <q> page:

- -
<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
-for short quotations that don't require paragraph breaks.</q></p>
- -

Browser default styling will render this as normal text put in quotes to indicate a quotation, like so:

- -

The quote element — <q> — is intended for short quotations that don't require paragraph breaks.

- -

Citations

- -

The content of the {{htmlattrxref("cite","blockquote")}} attribute sounds useful, but unfortunately browsers, screenreaders, etc. don't really do much with it. There is no way to get the browser to display the contents of cite, without writing your own solution using JavaScript or CSS. If you want to make the source of the quotation available on the page you need to make it available in the text via a link or some other appropriate way.

- -

There is a {{htmlelement("cite")}} element, but this is meant to contain the title of the resource being quoted, e.g. the name of the book. There is no reason however why you couldn't link the text inside <cite> to the quote source in some way:

- -
<p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
-<cite>MDN blockquote page</cite></a>:
-</p>
-
-<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
-  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
-  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
-</blockquote>
-
-<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
-for short quotations that don't require paragraph breaks.</q> -- <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">
-<cite>MDN q page</cite></a>.</p>
- -

Citations are styled in italic font by default. You can see this code at work in our quotations.html example.

- -

Active learning: Who said that?

- -

Time for another active learning example! In this example we'd like you to:

- -
    -
  1. Turn the middle paragraph into a blockquote, which includes a cite attribute.
  2. -
  3. Turn part of the third paragraph into an inline quote, which includes a cite attribute.
  4. -
  5. Include a <cite> element for each link to say what the title of the quoted source is.
  6. -
- -

The citation sources you need are:

- - - -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code_2', 700, 450, "", "", "hide-codepen-jsfiddle") }}

- -

Abbreviations

- -

Another fairly common element you'll meet when looking around the Web is {{htmlelement("abbr")}} — this is used to wrap around an abbreviation or acronym, and provide a full expansion of the term (included inside a {{htmlattrxref("title")}} attribute.) Let's look at a couple of examples:

- -
<p>We use <abbr title="Hypertext Markup Language">HTML</abbr> to structure our web documents.</p>
-
-<p>I think <abbr title="Reverend">Rev.</abbr> Green did it in the kitchen with the chainsaw.</p>
- -

These will come out looking something like this (the expansion will appear in a tooltip when the term is hovered over):

- -

We use HTML to structure our web documents.

- -

I think Rev. Green did it in the kitchen with the chainsaw.

- -
-

Note: There is another element, {{htmlelement("acronym")}}, which basically does the same thing as <abbr>, and was intended specifically for acronyms rather than abbreviations. This however has fallen into disuse — it wasn't supported in browsers as well as <abbr>, and has such a similar function that it was considered pointless to have both. Just use <abbr> instead.

-
- -

Active learning: marking up an abbreviation

- -

For this simple active learning assignment, we'd like you to simply mark up an abbreviation. You can use our sample below, or replace it with one of your own. 

- - - -

{{ EmbedLiveSample('Playable_code_3', 700, 300, "", "", "hide-codepen-jsfiddle") }}

- -

Marking up contact details

- -

HTML has an element for marking up contact details — {{htmlelement("address")}}. This simply wraps around your contact details, for example:

- -
<address>
-  <p>Chris Mills, Manchester, The Grim North, UK</p>
-</address>
- -

One thing to remember however is that the {{htmlelement("address")}} element is meant for marking up the contact details of the person who wrote the HTML document, not any address. So the above would only be ok if Chris had written the document the markup appears on. Note that something like this would also be ok:

- -
<address>
-  <p>Page written by <a href="../authors/chris-mills/">Chris Mills</a>.</p>
-</address>
- -

Superscript and subscript

- -

You will occasionally need to use superscript and subscript when marking up items like dates, chemical formulae, and mathematical equations so they have the correct meaning. The {{htmlelement("sup")}} and {{htmlelement("sub")}} elements handle this job. For example:

- -
<p>My birthday is on the 25<sup>th</sup> of May 2001.</p>
-<p>Caffeine's chemical formula is C<sub>8</sub>H<sub>10</sub>N<sub>4</sub>O<sub>2</sub>.</p>
-<p>If x<sup>2</sup> is 9, x must equal 3 or -3.</p>
- -

The output of this code looks like so:

- -

My birthday is on the 25th of May 2001.

- -

Caffeine's chemical formula is C8H10N4O2.

- -

If x2 is 9, x must equal 3 or -3.

- -

Representing computer code

- -

There are a number of elements available for marking up computer code using HTML:

- - - -

Let's look at a few examples. You should try having a play with these (try grabbing a copy of our other-semantics.html sample file):

- -
<pre><code>var para = document.querySelector('p');
-
-para.onclick = function() {
-  alert('Owww, stop poking me!');
-}</code></pre>
-
-<p>You shouldn't use presentational elements like <code>&lt;font&gt;</code> and <code>&lt;center&gt;</code>.</p>
-
-<p>In the above JavaScript example, <var>para</var> represents a paragraph element.</p>
-
-
-<p>Select all the text with <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + <kbd>A</kbd>.</p>
-
-<pre>$ <kbd>ping mozilla.org</kbd>
-<samp>PING mozilla.org (63.245.215.20): 56 data bytes
-64 bytes from 63.245.215.20: icmp_seq=0 ttl=40 time=158.233 ms</samp></pre>
- -

The above code will look like so:

- -

{{ EmbedLiveSample('Representing_computer_code','100%',300, "", "", "hide-codepen-jsfiddle") }}

- -

Marking up times and dates

- -

HTML also provides the {{htmlelement("time")}} element for marking up times and dates in a machine-readable format. For example:

- -
<time datetime="2016-01-20">20 January 2016</time>
- -

Why is this useful? Well, there are many different ways that humans write down dates. The above date could be written as:

- - - -

But these different forms cannot be easily recognised by computers — what if you wanted to automatically grab the dates of all events in a page and insert them into a calendar? The {{htmlelement("time")}} element allows you to attach an unambiguous, machine-readable time/date for this purpose.

- -

The basic example above just provides a simple machine readable date, but there are many other options that are possible, for example:

- -
<!-- Standard simple date -->
-<time datetime="2016-01-20">20 January 2016</time>
-<!-- Just year and month -->
-<time datetime="2016-01">January 2016</time>
-<!-- Just month and day -->
-<time datetime="01-20">20 January</time>
-<!-- Just time, hours and minutes -->
-<time datetime="19:30">19:30</time>
-<!-- You can do seconds and milliseconds too! -->
-<time datetime="19:30:01.856">19:30:01.856</time>
-<!-- Date and time -->
-<time datetime="2016-01-20T19:30">7.30pm, 20 January 2016</time>
-<!-- Date and time with timezone offset-->
-<time datetime="2016-01-20T19:30+01:00">7.30pm, 20 January 2016 is 8.30pm in France</time>
-<!-- Calling out a specific week number-->
-<time datetime="2016-W04">The fourth week of 2016</time>
- -

Summary

- -

That marks the end of our study of HTML text semantics. Bear in mind that what you have seen during this course is not an exhaustive list of HTML text elements — we wanted to try to cover the essentials, and some of the more common ones you will see in the wild, or at least might find interesting. To find way more HTML elements, you can take a look at our HTML element reference (the Inline text semantics section would be a great place to start.) In the next article we will look at the HTML elements you'd use to structure the different parts of an HTML document.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introducao_ao_html/index.html b/files/pt-pt/learn/html/introducao_ao_html/index.html deleted file mode 100644 index 6e2ac788fd..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Introdução ao HTML -slug: Learn/HTML/Introducao_ao_HTML -tags: - - CodingScripting - - Estrutura - - HTML - - Hiperligações - - Introdução ao HTML - - Texto - - head - - semántica -translation_of: Learn/HTML/Introduction_to_HTML ---- -
{{LearnSidebar}}
- -

Na sua essência, {{glossary("HTML")}} é uma linguagem bastante simples, composta por elementos que podem ser aplicados em partes de texto para lhes dar um significado diferente num documento (É um parágrafo? Uma lista com marcas? É parte de uma tabela?), estruturar um documento em secções lógicas (Tem um cabeçalho? Três colunas de conteúdo? Um menu de navegação?) e incorporar conteúdo como imagens e vídeos numa página. Este módulo irá apresentar as duas primeiras aplicações e introduzir os conceitos e a sintaxe fundamentais que você precisa de saber para compreender HTML.

- -

Pré-requisitos

- -

Antes de começar este módulo, não precisa de ter qualquer conhecimento prévio de  HTML, mas deve pelo menos ter alguma familiaridade com utilização de computadores, e utilização passiva da Web (ou seja, apenas na perspectiva de consumidor e não de criação e publicação de conteúdos). Deverá ter um ambiente de trabalho básico configurado de acordo com as indicações que pode encontrar em Instalar software básico, e compreender como se criam e gerem ficheiros, como indicado na secção Lidar com ficheiros — estas duas secções fazem ambas parte do nosso módulo completo de iniciação em Primeiros passos na web.

- -
-

Nota: Se está a trabalhar num computador, tablet ou outro dispositivo em que não tem possibilidade de criar ficheiros, pode testar a maioria dos exemplos de código num programa de edição de código online como o JSBin ou o Thimble.

-
- -

Guias

- -

Este módulo contém os seguintes artigos, os quais vão guiá-lo ao longo da teoria básica de HTML, e dar-lhe amplas oportunidades para experimentar o que aprendeu.

- -
-
Começar com HTML
-
Para começar, cobrimos as bases absolutas do HTML — definir elementos, atributos e todos os termos importantes de que já ouviu falar, e como se encaixam na linguagem. Também mostramos a estrutura de um elemento HTML, a estrutura de uma página HTML típica e explicamos outras funcionalidades básicas mas importantes da linguagem. Ao longo do caminho, vamos brincar com algum HTML, para lhe despertar o interesse!
-
O que lhe vai no cabeçalho? Metadadados em HTML
-
O cabeçalho de um documento HTML é parte que não é mostrada no navegador quando a página é carregada. Contém informação como o título da página ({{htmlelement("title")}}), ligações para {{glossary("CSS")}} (se quiser estilizar o conteúdo HTML com CSS), ligações a ícones personalizados, e metadados (dados sobre HTML, por exemplo, quem o escreveu e palavras-chave importantes que descrevem o documento).
-
Fundamentos do texto HTML
-
Uma das principais funções do HTML é atribuir significado (semântica) ao texto, para que o navegador o apresente corretamente. Este artigo explora como utilizar HTML para repartir o bloco de texto em títulos e parágrafos, dar ênfase/importância a palavras, criar listas e mais.
-
Criar hiperligações
-
Hiperligações são muito importantes — são o que torna a internet na internet. Este artigo mostra a sintaxe necessária para criar uma ligação (um link), e discute boas práticas a ter quando se criam hiperligações.
-
Formatação avançada de texto
-
Há muitos outros elementos em HTML para formatar texto, que não vimos em Fundamentos do texto HTML. Estes elementos são menos conhecidos, mas é útil conhecê-los. Neste artigo aprenderá a demarcar citações, listas de descrições, código de computador e outro texto relacionado, texto sobre e por baixo da linha, informação de contactos e mais.
-
Estrutura do documento e do website
-
Além de definir partes individuais da página (como parágrafos e imagens), HTML também define secções do site (como cabeçalho, menu de navegação, coluna principal de conteúdo). Este artigo aborda como planear a estrutura básica de um site e como escrever HTML que represente essa estrutura.
-
Depurar HTML
-
É ótimo escrever HTML, mas como proceder se alguma coisa correr mal e não conseguir descobrir em que parte do código está o erro? Este artigo introduz algumas ferramentas que pode utilizar.
-
- -

Avaliações

- -

Estas avaliações testam o seu conhecimento das bases de HTML abrangidas nos guias suprarreferidos.

- -
-
Demarcar uma carta
-
Todos aprendemos a escrever uma carta mais cedo ou mais tarde; e é um exemplo útil para testar as nossas capacidades de formatação de texto! Nesta avaliação, damos-lhe uma carta para demarcar.
-
Estruturar uma página de conteúdo
-
Esta avaliação testa a sua capacidade de recorrer a HTML para estruturar uma página de conteúdo simples, que contém cabeçalho, rodapé, menu de navegação, conteúdo principal e barra lateral.
-
- -

Consultar também

- -
-
Básicos de literacia da Web 1 (inglês)
-
Um curso excelente da fundação Mozilla que explora e testa muitas das habilidades faladas no módulo de Introdução ao HTML. Os principiantes familiarizam-se com a leitura, escrita e participação na Web neste módulo de seis partes. Descubra as fundações da Web através da produção e colaboração.
-
diff --git a/files/pt-pt/learn/html/introducao_ao_html/iniciacao_html/index.html b/files/pt-pt/learn/html/introducao_ao_html/iniciacao_html/index.html deleted file mode 100644 index 981b23e556..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/iniciacao_html/index.html +++ /dev/null @@ -1,612 +0,0 @@ ---- -title: Começar com HTML -slug: Learn/HTML/Introducao_ao_HTML/Iniciacao_HTML -tags: - - Comentário - - Elemento - - Guía - - HTML - - Principiante - - atributo - - espaço em branco - - referência de entidade -translation_of: Learn/HTML/Introduction_to_HTML/Getting_started ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/HTML/Introducao_ao_HTML/Os_metadados_de_head_em_HTML", "Learn/HTML/Introducao_ao_HTML")}}
- -

Neste artigo nós iremos abranger os básicos absolutos de HTML, para o iniciar — nós definimos os elementos, atributos, e todos os outros termos importantes que já poderá ter ouvido, e onde os incorporar na linguagem. Nós também mostramos como é que o elemento de HTML é estruturado, como é que uma página HTML é estruturada, e explicar outras funcionalidades de linguagem básica importantes. E nós iremos algumas demonstrações de algum HTML, para o motivar!

- - - - - - - - - - - - -
Pré-requisitos:Basic computer literacy, basic software installed, and basic knowledge of working with files.
Objetivo:To gain basic familiarity with the HTML language, and get some practice writing a few HTML elements.
- -

O que é HTML?

- -

{{glossary("HTML")}} (Linguagem de Marcação de Hipertexto) não é uma linguagem de programação; é uma linguagem de marcação utilizada para comunicar ao seu navegador como estruturar as páginas da Web que visita. Este pode ser tão complicado ou tão simples como o programador da Web o desejar. HTML consiste em uma série de  {{glossary("Element", "elementos")}}, que utiliza para incluir, ou marcar diferentes partes do conteúdo para que este apareça ou atue de uma determinada maneira. A inclusão de {{glossary("Tag", "etiquetas")}} pode tornar uma parte do conteúdo em uma hiperligação para interligar com outra página na Web, colocar as palavras em itálico, e assim por diante. Por exemplo, siga a seguinte linha de conteúdo:

- -
My cat is very grumpy
- -

Se quisermos que a linha esteja demarcada, podemos especificar que é um parágrafo, encerrando-a num elemento com tag de parágrafo ({{htmlelement("p")}}) :

- -
<p>My cat is very grumpy</p>
- -

Anatomia de um elemento HTML

- -

Vamos explorar o nosso elemento parágrafo um pouco mais:

- -

- -

As partes principais do nosso elemento são:

- -
    -
  1. A tag de abertura: Isto consiste no nome do elemento (neste caso, p), envolta por colchetes angulares de abertura ( < ) e fecho ( > ). Isto especifica onde o elemento começa, ou onde começa a ter efeito - neste caso, onde está o início do parágrafo.
  2. -
  3. A tag de fecho: Isto é o mesmo que a tag de abertura, só que inclui um traço ( \ ) antes do nome do elemento. Isto indica onde é que o elemento acaba - neste caso, onde é o fim do parágrafo. Esquecer-se de incluir uma tag de fecho é um erro comum de principiante e pode levar a resultados estranhos.
  4. -
  5. O conteúdo: É o conteúdo do elemento, que neste caso é só texto.
  6. -
  7. O elemento: A tag de abertura mais a tag de fecho mais o conteúdo é igual ao elemento.
  8. -
- -

Aprendizagem ativa: criar o seu primeiro HTML

- -

Edit the line below in the Input area by wrapping it with the tags <em> and </em> (put <em> before it to open the element, and </em> after it, to close the element) — this should give the line italic emphasis! You'll be able to see your changes update live in the Output area.

- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code', 700, 300) }}

- -

Nesting elements

- -

You can put elements inside other elements too — this is called nesting. If we wanted to state that our cat is very grumpy, we could wrap the word "very" in a {{htmlelement("strong")}} element, which means that the word is to be strongly emphasized:

- -
<p>My cat is <strong>very</strong> grumpy.</p>
- -

You do however need to make sure that your elements are properly nested: in the example above we opened the p element first, then the strong element, therefore we have to close the strong element first, then the p. The following is incorrect:

- -
<p>My cat is <strong>very grumpy.</p></strong>
- -

The elements have to open and close correctly so they are clearly inside or outside one another. If they overlap like above, then your web browser will try to make a best guess at what you were trying to say, and you may well get unexpected results. So don't do it!

- -

Block versus inline elements

- -

There are two important categories of elements in HTML, which you should know about — block-level elements and inline elements.

- - - -

Take the following example:

- -
<em>first</em><em>second</em><em>third</em>
-
-<p>fourth</p><p>fifth</p><p>sixth</p>
-
- -

{{htmlelement("em")}} is an inline element, so as you can see below, the first three elements sit on the same line as one another with no space in between. On the other hand, {{htmlelement("p")}} is a block-level element, so each element appears on a new line, with space above and below each (the spacing is due to default CSS styling that the browser applies to paragraphs).

- -

{{ EmbedLiveSample('Block_versus_inline_elements', 700, 200) }}

- -
-

Nota: HTML5 redefined the element categories in HTML5: see Element content categories. While these definitions are more accurate and less ambiguous than the ones that went before, they are a lot more complicated to understand than "block" and "inline", so we will stick with these throughout this topic.

-
- -
-

Nota: You can find useful reference pages that include lists of block and inline elements — see Block-level elements and Inline elements.

-
- -

Elementos vazios

- -

Not all elements follow the above pattern of opening tag, content, closing tag. Some elements consist only of a single tag, which is usually used to insert/embed something in the document at the place it is included. For example, the {{htmlelement("img")}} element embeds an image file onto a page in the position it is included in:

- -
<img src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png">
- -

This would output the following on your page:

- -

{{ EmbedLiveSample('Empty_elements', 700, 300) }}

- -
-

Nota: Empty elements are also sometimes called void elements.

-
- -

Atributos

- -

Elements can also have attributes, which look like this:

- -

&lt;p class="editor-note">My cat is very grumpy&lt;/p>

- -

Attributes contain extra information about the element which you don't want to appear in the actual content. In this case, the class attribute allows you to give the element an identifying name that can be later used to target the element with style information and other things.

- -

An attribute should have:

- -
    -
  1. A space between it and the element name (or the previous attribute, if the element already has one or more attributes.)
  2. -
  3. The attribute name, followed by an equals sign.
  4. -
  5. An attribute value, with opening and closing quote marks wrapped around it.
  6. -
- -

Aprendizagem ativa: Adicionar atributos a um elemento

- -

Another example of an element is {{htmlelement("a")}} — this stands for anchor and will make the piece of text it wraps around into a hyperlink. This can take a number of attributes, but several are as follows:

- - - -

Edit the line below in the Input area to turn it into a link to your favourite website. First, add the <a> element. Second, add the href attribute and the title attribute. Lastly, specify target attribute to open the link in the new tab. You'll be able to see your changes update live in the Output area. You should see a link that when hovered over displays the title attribute's content, and when clicked navigates to the web address in the href element. Remember that you need to include a space between the element name, and each attribute.

- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code2', 700, 300) }}

- -

Atributos de booliano

- -

You'll sometimes see attributes written without values — this is perfectly allowed. These are called boolean attributes, and they can only have one value, which is generally the same as the attribute name. As an example, take the {{htmlattrxref("disabled", "input")}} attribute, which you can assign to form input elements if you want them to be disabled (greyed out) so the user can't enter any data in them.

- -
<input type="text" disabled="disabled">
- -

As shorthand, it is perfectly allowable to write this as follows (we've also included a non-disabled form input element for reference, to give you more of an idea what is going on):

- -
<input type="text" disabled>
-
-<input type="text">
-
- -

Both will give you an output as follows:

- -

{{ EmbedLiveSample('Boolean_attributes', 700, 100) }}

- -

Omitir aspas em volta de valores de atributo

- -

When you look around the World Wide Web, you'll come across all kind of strange markup styles, including attribute values without quotes. This is allowable in certain circumstances, but will break your markup in others. For example, if we revisit our link example from earlier, we could write a basic version with only the href attribute, like this:

- -
<a href=https://www.mozilla.org/>favourite website</a>
- -

However, as soon as we add the title attribute in this style, things will go wrong:

- -
<a href=https://www.mozilla.org/ title=The Mozilla homepage>favourite website</a>
- -

At this point the browser will misinterpret your markup, thinking that the title attribute is actually three attributes — a title attribute with the value "The", and two boolean attributes, Mozilla and homepage. This is obviously not what was intended, and will cause errors or unexpected behaviour in the code, as seen in the live example below. Try hovering over the link to see what the title text is!

- -

{{ EmbedLiveSample('Omitting_quotes_around_attribute_values', 700, 100) }}

- -

Our advice is to always include the attribute quotes — it avoids such problems, and results in more readable code too.

- -

Aspas simples ou duplas?

- -

In this article you'll notice that the attributes are all wrapped in double quotes. You might however see single quotes in some people's HTML. This is purely a matter of style, and you can feel free to choose which one you prefer. Both the following lines are equivalent:

- -
<a href="http://www.example.com">A link to my example.</a>
-
-<a href='http://www.example.com'>A link to my example.</a>
- -

You should however make sure you don't mix them together. The following will go wrong!

- -
<a href="http://www.example.com'>A link to my example.</a>
- -

If you've used one type of quote in your HTML, you can include the other type of quote without causing any problems:

- -
<a href="http://www.example.com" title="Isn't this fun?">A link to my example.</a>
- -

However if you want to include a quote within the quotes where both the quotes are of the same type(single quote or double quote), you'll have to use HTML entities for the quotes.

- -

Anatomia de uma documento HTML

- -

That wraps up the basics of individual HTML elements, but they aren't very useful on their own. Now we'll look at how individual elements are combined to form an entire HTML page:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-    <title>My test page</title>
-  </head>
-  <body>
-    <p>This is my page</p>
-  </body>
-</html>
- -

Here we have:

- -
    -
  1. <!DOCTYPE html>: The doctype. In the mists of time, when HTML was young (about 1991/2), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML, which could mean automatic error checking and other useful things. They used to look something like this: - -
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    - However, these days no one really cares about them, and they are really just a historical artifact that needs to be included for everything to work right. <!DOCTYPE html> is the shortest string of characters that counts as a valid doctype; that's all you really need to know.
  2. -
  3. <html></html>: The {{htmlelement("html")}} element. This element wraps all the content on the entire page, and is sometimes known as the root element.
  4. -
  5. <head></head>: The {{htmlelement("head")}} element. This element acts as a container for all the stuff you want to include on the HTML page that isn't the content you are showing to your page's viewers. This includes things like keywords and a page description that you want to appear in search results, CSS to style our content, character set declarations, and more. You'll learn more about this in the next article in the series.
  6. -
  7. <meta charset="utf-8">: This element sets the character set your document should use to UTF-8, which includes most characters from the vast majority of human written languages. Essentially it can now handle any textual content you might put on it. There is no reason not to set this, and it can help avoid some problems later on.
  8. -
  9. <title></title>: The {{htmlelement("title")}} element. This sets the title of your page, which is the title that appears in the browser tab the page is loaded in, and is used to describe the page when you bookmark/favourite it.
  10. -
  11. <body></body>: The {{htmlelement("body")}} element. This contains all the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks, or whatever else.
  12. -
- -

Aprendizagem ativa: Adicionar alguns recursos a um documento HTML

- -

If you want to experiment with writing some HTML on your local computer, you can:

- -
    -
  1. Copy the HTML page example listed above.
  2. -
  3. Create a new file in your text editor.
  4. -
  5. Paste the code into the new text file.
  6. -
  7. Save the file as index.html.
  8. -
- -
-

Nota: You can also find this basic HTML template on the MDN Learning Area Github repo.

-
- -

You can now open this file in a web browser to see what the rendered code looks like, and then edit the code and refresh the browser to see what the result is. Initially it will look like this:

- -

A simple HTML page that says This is my pageSo in this exercise, you can edit the code locally on your computer, as outlined above, or you can edit it in the editable sample window below (the editable sample window represents just the contents of the {{htmlelement("body")}} element, in this case.) We'd like you to have a go at implementing the following steps:

- - - -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code3', 700, 600) }}

- -

Espaço em branco em HTML

- -

In the above examples you may have noticed that a lot of whitespace is included in the code listings — this is not necessary at all; the two following code snippets are equivalent:

- -
<p>Dogs are silly.</p>
-
-<p>Dogs        are
-         silly.</p>
- -

No matter how much whitespace you use (which can include space characters, but also line breaks), the HTML parser reduces each one down to a single space when rendering the code. So why use so much whitespace? The answer is readability — it is so much easier to understand what is going on in your code if you have it nicely formatted, and not just bunched up together in a big mess. In our HTML we've got each nested element indented by two spaces more than the one it is sitting inside. It is up to you what style of formatting you use (how many spaces for each level of indentation, for example), but you should consider using some kind of formatting.

- -

Referências de entidade: incluindo carateres especiais em HTML

- -

In HTML, the characters <, >,",' and & are special characters. They are parts of the HTML syntax itself, so how do you include one of these characters in your text, for example if you really want to use an ampersand or less than sign, and not have it interpreted as code as some browsers may do?

- -

We have to use character references — special codes that represent characters, and can be used in these exact circumstances. Each character reference is started with an ampersand (&), and ended by a semi-colon (;).

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Caráter literalReferência de caráter equivalente
<&lt;
>&gt;
"&quot;
'&apos;
&&amp;
- -

In the below example, you can see two paragraphs, which are talking about web technologies:

- -
<p>In HTML, you define a paragraph using the <p> element.</p>
-
-<p>In HTML, you define a paragraph using the &lt;p&gt; element.</p>
- -

In the live output below, you can see that the first paragraph has gone wrong, because the browser thinks that the second instance of <p> is starting a new paragraph. The second paragraph looks fine, because we have replaced the angle brackets with character references.

- -

{{ EmbedLiveSample('Entity_references_including_special_characters_in_HTML', 700, 200) }}

- -
-

Nota: A chart of all the available HTML character entity references can be found on Wikipedia: List of XML and HTML character entity references.

-
- -

Comentários de HTML

- -

In HTML, as with most programming languages, there is a mechanism available to write comments in the code — comments are ignored by the browser and invisible to the user, and their purpose is to allow you to include comments in the code to say how your code works, what the different parts of the code do, etc. This can be very useful if you return to a code base that you've not worked on for six months, and can't remember what you did — or if you hand your code over to someone else to work on.

- -

To turn a section of content inside your HTML file into a comment, you need to wrap it in the special markers <!-- and -->, for example:

- -
<p>I'm not inside a comment</p>
-
-<!-- <p>I am!</p> -->
- -

As you can see below, the first paragraph appears in the live output, but the second one doesn't.

- -

{{ EmbedLiveSample('HTML_comments', 700, 100) }}

- -

Resumo

- -

You've reached the end of the article — we hope you enjoyed your tour of the very basics of HTML! At this point you should understand what the language looks like, how it works at a basic level, and be able to write a few elements and attributes. This is a perfect place to be right now, as in subsequent articles in the module we will go into some of the things you have already looked at in a lot more detail, and introduce some new features of the language. Stay tuned!

- -
-

Note: At this point, as you start to learn more about HTML, you might also want to start to explore the basics of Cascading Style Sheets, or CSS. CSS is the language you use to style your web pages (whether e.g. changing the font or colors, or altering the page layout). HTML and CSS go very well together, as you'll soon discover.

-
- -

Consulte também

- - - -
{{NextMenu("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML")}}
- -
- - - - - -
diff --git a/files/pt-pt/learn/html/introducao_ao_html/os_metadados_de_head_em_html/index.html b/files/pt-pt/learn/html/introducao_ao_html/os_metadados_de_head_em_html/index.html deleted file mode 100644 index 099166b821..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/os_metadados_de_head_em_html/index.html +++ /dev/null @@ -1,346 +0,0 @@ ---- -title: O que está em "head"? Metadados em HTML -slug: Learn/HTML/Introducao_ao_HTML/Os_metadados_de_head_em_HTML -tags: - - Guía - - HTML - - Idioma - - Meta - - Principiante - - head - - metadados -translation_of: Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introducao_ao_HTML")}}
- -

{{glossary("Head", "Head")}} de um documento HTML é a parte que não é exibida no navegador da Web quando a página é carregada. Este contém a informação, tais como o {{htmlelement("title", "título")}} da página, hiperligações para {{glossary("CSS")}} (se pretender estilizar o seu conteúdo HTML com CSS), hiperligações para favicons personalizados, e outros metadados (dados sobre o HTML, tais como quem o escreveu, e palavras-chave importantes que descrevem o documento.) Neste artigo nós iremos abranger todas as coisas acima e muito mais, para lhe dar bons conceitos básicos para lidar com a marcação e outro código que deverá estar no seu head.

- - - - - - - - - - - - -
Pré-requisitos:Basic HTML familiarity, as covered in Getting started with HTML.
Objetivo:To learn about the HTML head, what its purpose is, the most important items it can contain, and what effect it can have on the HTML document.
- -

O que é head no HTML?

- -

Let's revisit the simple HTML document we covered in the previous article:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-    <title>My test page</title>
-  </head>
-  <body>
-    <p>This is my page</p>
-  </body>
-</html>
- -

The HTML head is the contents of the {{htmlelement("head")}} element — unlike the contents of the {{htmlelement("body")}} element (which are displayed on the page when loaded in a browser), the head's content is not displayed on the page. Instead, the head's job is to contain {{glossary("Metadata", "metadata")}} about the document. In the above example, the head is quite small:

- -
<head>
-  <meta charset="utf-8">
-  <title>My test page</title>
-</head>
- -

In larger pages however, the head can get quite full of items — try going to some of your favorite websites and using the developer tools to check out their head contents. Our aim here is not to show you how to use everything that can possibly be put in the head, but rather to teach you how to use the most obvious things you'll want to include in the head, and give you some familiarity. Let's get started.

- -

Adding a title

- -

We've already seen the {{htmlelement("title")}} element in action — this can be used to add a title to the document. This however can get confused with the {{htmlelement("h1")}} element, which is used to add a top level heading to your body content — this is also sometimes referred to as the page title. But they are different things!

- - - -

Active learning: Inspecting a simple example

- -
    -
  1. To start off this active learning, we'd like you to go to our GitHub repo and download a copy of our title-example.html page. To do this, either - -
      -
    1. Copy and paste the code out of the page and into a new text file in your code editor, then save it in a sensible place.
    2. -
    3. Press the "Raw" button on the page, which causes the raw code to appear in a new browser tab. Next, from your browser's menu choose File > Save Page As... in your browser's menu then choose a place to save the file.
    4. -
    -
  2. -
  3. Now open the file in your browser. You should see something like this: -

    A simple web page with the title set to <title> element, and the <h1> set to <h1> element.It should now be completely obvious where the <h1> content appears, and where the <title> content appears!

    -
  4. -
  5. You should also try opening the code up in your code editor, editing the contents of these elements, then refreshing the page in your browser. Have some fun with it.
  6. -
- -

The <title> element contents are also used in other ways. For example, if you try bookmarking the page (Bookmarks > Bookmark This Page or the star icon in the URL bar in Firefox), you will see the <title> contents filled in as the suggested bookmark name.

- -

A webpage being bookmarked in firefox; the bookmark name has been automatically filled in with the contents of the <title> element

- -

The <title> contents are also used in search results, as you'll see below.

- -

Metadata: the <meta> element

- -

Metadata is data that describes data, and HTML has an "official" way of adding metadata to a document — the {{htmlelement("meta")}} element. Of course, the other stuff we are talking about in this article could also be thought of as metadata too. There are a lot of different types of <meta> element that can be included in your page's <head>, but we won't try to explain them all at this stage, as it would just get too confusing. Instead, we'll explain a few things that you might commonly see, just to give you an idea.

- -

Specifying your document's character encoding

- -

In the example we saw above, this line was included:

- -
<meta charset="utf-8">
- -

This element simply specifies the document's character encoding — the character set that the document is permitted to use. utf-8 is a universal character set that includes pretty much any character from any human language. This means that your web page will be able to handle displaying any language; it's therefore a good idea to set this on every web page you create! For example, your page could handle English and Japanese just fine:

- -

a web page containing English and Japanese characters, with the character encoding set to universal, or utf-8. Both languages display fine,If you set your character encoding to ISO-8859-1, for example (the character set for the Latin alphabet), your page rendering would be all messed up:

- -

a web page containing English and Japanese characters, with the character encoding set to latin. The Japanese characters don't display correctly

- -

Active learning: Experiment with character encoding

- -

To try this out, revisit the simple HTML template you obtained in the previous section on <title> (the title-example.html page), try changing the meta charset value to ISO-8859-1, and add the Japanese to your page. This is the code we used:

- -
<p>Japanese example: ご飯が熱い。</p>
- -

Adding an author and description

- -

Many <meta> elements include name and content attributes:

- - - -

Two such meta elements that are useful to include on your page define the author of the page, and provide a concise description of the page. Let's look at an example:

- -
<meta name="author" content="Chris Mills">
-<meta name="description" content="The MDN Learning Area aims to provide
-complete beginners to the Web with all they need to know to get
-started with developing web sites and applications.">
- -

Specifying an author is useful in a few ways: it is useful to be able to work out who wrote the page, if you want to contact them with questions about the content. Some content management systems have facilities to automatically extract page author information and make it available for such purposes.

- -

Specifying a description that includes keywords relating to the content of your page is useful as it has the potential to make your page appear higher in relevant searches performed in search engines (such activities are termed Search Engine Optimization, or {{glossary("SEO")}}.)

- -

Active learning: The description's use in search engines

- -

The description is also used on search engine result pages. Let's go through an exercise to explore this

- -
    -
  1. Go to the front page of The Mozilla Developer Network.
  2. -
  3. View the page's source (Right/Ctrl + click on the page, choose View Page Source from the context menu.)
  4. -
  5. Find the description meta tag. It will look like this: -
    <meta name="description" content="The Mozilla Developer Network (MDN) provides
    -information about Open Web technologies including HTML, CSS, and APIs for both
    -Web sites and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
    -
  6. -
  7. Now search for "Mozilla Developer Network" in your favorite search engine (We used Yahoo.) You'll notice the description <meta> and <title> element content used in the search result — definitely worth having! -

    A Yahoo search result for "Mozilla Developer Network"

    -
  8. -
- -
-

Note: In Google, you will see some relevant subpages of MDN listed below the main MDN homepage link — these are called sitelinks, and are configurable in Google's webmaster tools — a way to make your site's search results better in the Google search engine.

-
- -
-

Note: Many <meta> features just aren't used any more. For example, the keyword <meta> element (<meta name="keywords" content="fill, in, your, keywords, here">) — which is supposed to provide keywords for search engines to determine relevance of that page for different search terms — is ignored by search engines, because spammers were just filling the keyword list with hundreds of keywords, biasing results.

-
- -

Other types of metadata

- -

As you travel around the web, you'll find other types of metadata, too. A lot of the features you'll see on websites are proprietary creations, designed to provide certain sites (such as social networking sites) with specific pieces of information they can use.

- -

For example, Open Graph Data is a metadata protocol that Facebook invented to provide richer metadata for websites. In the MDN sourcecode, you'll find this:

- -
<meta property="og:image" content="https://developer.cdn.mozilla.net/static/img/opengraph-logo.dc4e08e2f6af.png">
-<meta property="og:description" content="The Mozilla Developer Network (MDN) provides
-information about Open Web technologies including HTML, CSS, and APIs for both Web sites
-and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
-<meta property="og:title" content="Mozilla Developer Network">
- -

One effect of this is that when you link to MDN on facebook, the link appears along with an image and description: a richer experience for users.

- -

Open graph protocol data from the MDN homepage as displayed on facebook, showing an image, title, and description.Twitter also has its own similar proprietary metadata, which has a similar effect when the site's URL is displayed on twitter.com. For example:

- -
<meta name="twitter:title" content="Mozilla Developer Network">
- -

Adding custom icons to your site

- -

To further enrich your site design, you can add references to custom icons in your metadata, and these will be displayed in certain contexts.

- -

The humble favicon, which has been around for many years, was the first icon of this type, a 16 x 16 pixel icon used in multiple places. You'll see favicons displayed in the browser tab containing each open page, and next to bookmarked pages in the bookmarks panel.

- -

A favicon can be added to your page by:

- -
    -
  1. Saving it in the same directory as the site's index page, saved in .ico format (most browsers will support favicons in more common formats like .gif or .png, but using the ICO format will ensure it works as far back as Internet Explorer 6.)
  2. -
  3. Adding the following line into your HTML <head> to reference it: -
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    -
  4. -
- -

Here is an example of a favicon in a bookmarks panel:

- -

The Firefox bookmarks panel, showing a bookmarked example with a favicon displayed next to it.

- -

There are lots of other icon types to consider these days as well. For example, you'll find this in the source code of the MDN homepage:

- -
<!-- third-generation iPad with high-resolution Retina display: -->
-<link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://developer.cdn.mozilla.net/static/img/favicon144.a6e4162070f4.png">
-<!-- iPhone with high-resolution Retina display: -->
-<link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://developer.cdn.mozilla.net/static/img/favicon114.0e9fabd44f85.png">
-<!-- first- and second-generation iPad: -->
-<link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://developer.cdn.mozilla.net/static/img/favicon72.8ff9d87c82a0.png">
-<!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
-<link rel="apple-touch-icon-precomposed" href="https://developer.cdn.mozilla.net/static/img/favicon57.a2490b9a2d76.png">
-<!-- basic favicon -->
-<link rel="shortcut icon" href="https://developer.cdn.mozilla.net/static/img/favicon32.e02854fdcf73.png">
- -

The comments explain what each icon is used for — these elements cover things like providing a nice high resolution icon to use when the website is saved to an iPad's home screen.

- -

Don't worry too much about implementing all these types of icon right now — this is a fairly advanced feature, and you won't be expected to have knowledge of this to progress through the course. The main purpose here is to let you know what such things are, in case you come across them while browsing other websites' source code.

- -

Applying CSS and JavaScript to HTML

- -

Just about all websites you'll use in the modern day will employ {{glossary("CSS")}} to make them look cool, and {{glossary("JavaScript")}} to power interactive functionality, such as video players, maps, games, and more. These are most commonly applied to a web page using the {{htmlelement("link")}} element and the {{htmlelement("script")}} element, respectively.

- - - -

Active learning: applying CSS and JavaScript to a page

- -
    -
  1. To start this active learning, grab a copy of our meta-example.html, script.js and style.css files, and save them on your local computer in the same directory. Make sure they are saved with the correct names and file extensions.
  2. -
  3. Open the HTML file in both your browser, and your text editor.
  4. -
  5. By following the information given above, add {{htmlelement("link")}} and {{htmlelement("script")}} elements to your HTML, so that your CSS and JavaScript are applied to your HTML.
  6. -
- -

If done correctly, when you save your HTML and refresh your browser you'll see that things have changed:

- -

Example showing a page with CSS and JavaScript applied to it. The CSS has made the page go green, whereas the JavaScript has added a dynamic list to the page.

- - - -
-

Note: If you get stuck in this exercise and can't get the CSS/JS to apply, try checking out our css-and-js.html example page.

-
- -

Setting the primary language of the document

- -

Finally, it's worth mentioning that you can (and really should) set the language of your page. This can be done by adding the lang attribute to the opening HTML tag (as seen in the meta-example.html and shown below.)

- -
<html lang="en-US">
- -

This is useful in many ways. Your HTML document will be indexed more effectively by search engines if its language is set (allowing it to appear correctly in language-specific results, for example), and it is useful to people with visual impairments using screen readers (for example, the word "six" exists in both French and English, but is pronounced differently.)

- -

You can also set subsections of your document to be recognised as different languages. For example, we could set our Japanese language section to be recognised as Japanese, like so:

- -
<p>Japanese example: <span lang="jp">ご飯が熱い。</span>.</p>
- -

These codes are defined by the ISO 639-1 standard. You can find more about them in Language tags in HTML and XML.

- -

Resumo

- -

That marks the end of our quickfire tour of the HTML head — there's a lot more you can do in here, but an exhaustive tour would be boring and confusing at this stage, and we just wanted to give you an idea of the most common things you'll find in there for now! In the next article we'll be looking at HTML text fundamentals.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML")}}

- -
- - - - - -
diff --git a/files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html b/files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html new file mode 100644 index 0000000000..882f2eec7b --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html @@ -0,0 +1,691 @@ +--- +title: Formatação avançada de texto +slug: Learn/HTML/Introducao_ao_HTML/Formatacao_avancada_texto +tags: + - Aprender + - Guía + - HTML + - Principiante + - Texto + - abreviatura + - semántica +translation_of: Learn/HTML/Introduction_to_HTML/Advanced_text_formatting +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}
+ +

There are many other elements in HTML for formatting text, which we didn't get to in the HTML text fundamentals article. The elements described in this article are less known, but still useful to know about (and this is still not a complete list by any means). Here you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more.

+ + + + + + + + + + + + +
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:To learn how to use lesser-known HTML elements to mark up advanced semantic features.
+ +

Description lists

+ +

In HTML text fundamentals, we walked through how to mark up basic lists in HTML, but we didn't mention the third type of list you'll occasionally come across — description lists. The purpose of these lists is to mark up a set of items and their associated descriptions, such as terms and definitions, or questions and answers. Let's look at an example of a set of terms and definitions:

+ +
soliloquy
+In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
+monologue
+In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
+aside
+In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information
+ +

Description lists use a different wrapper than the other list types — {{htmlelement("dl")}}; in addition each term is wrapped in a {{htmlelement("dt")}} (description term) element, and each description is wrapped in a {{htmlelement("dd")}} (description definition) element. Let's finish marking up our example:

+ +
<dl>
+  <dt>soliloquy</dt>
+  <dd>In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)</dd>
+  <dt>monologue</dt>
+  <dd>In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.</dd>
+  <dt>aside</dt>
+  <dd>In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought, or piece of additional background information.</dd>
+</dl>
+ +

The browser default styles will display description lists with the descriptions indented somewhat from the terms. MDN's styles follow this convention fairly closely, but also embolden the terms for extra definition.

+ +
+
soliloquy
+
In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
+
monologue
+
In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
+
aside
+
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.
+
+ +

Note that it is permitted to have a single term with multiple descriptions, for example:

+ +
+
aside
+
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.
+
In writing, a section of content that is related to the current topic, but doesn't fit directly into the main flow of content so is presented nearby (often in a box off to the side.)
+
+ +

Active learning: Marking up a set of definitions

+ +

It's time to try your hand at description lists; add elements to the raw text in the Input field so that it appears as a description list in the Output field. You could try using your own terms and descriptions if you like.

+ +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 350, "", "", "hide-codepen-jsfiddle") }}

+ +

Quotations

+ +

HTML also has features available for marking up quotations; which element you use depends on whether you are marking up a block or inline quotation.

+ +

Blockquotes

+ +

If a section of block level content (be it a paragraph, multiple paragraphs, a list, etc.) is quoted from somewhere else, you should wrap it inside a {{htmlelement("blockquote")}} element to signify this, and include a URL pointing to the source of the quote inside a {{htmlattrxref("cite","blockquote")}} attribute. For example, the following markup is taken from the MDN <blockquote> element page:

+ +
<p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
+Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
+ +

To turn this into a block quote, we would just do this:

+ +
<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
+  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
+  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
+</blockquote>
+ +

Browser default styling will render this as an indented paragraph, as an indicator that it is a quote; MDN does this, but also adds some extra styling:

+ +
+

The HTML <blockquote> Element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation.

+
+ +

Inline quotations

+ +

Inline quotations work in exactly the same way, except that they use the {{htmlelement("q")}} element. For example, the below bit of markup contains a quotation from the MDN <q> page:

+ +
<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
+for short quotations that don't require paragraph breaks.</q></p>
+ +

Browser default styling will render this as normal text put in quotes to indicate a quotation, like so:

+ +

The quote element — <q> — is intended for short quotations that don't require paragraph breaks.

+ +

Citations

+ +

The content of the {{htmlattrxref("cite","blockquote")}} attribute sounds useful, but unfortunately browsers, screenreaders, etc. don't really do much with it. There is no way to get the browser to display the contents of cite, without writing your own solution using JavaScript or CSS. If you want to make the source of the quotation available on the page you need to make it available in the text via a link or some other appropriate way.

+ +

There is a {{htmlelement("cite")}} element, but this is meant to contain the title of the resource being quoted, e.g. the name of the book. There is no reason however why you couldn't link the text inside <cite> to the quote source in some way:

+ +
<p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
+<cite>MDN blockquote page</cite></a>:
+</p>
+
+<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
+  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
+  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
+</blockquote>
+
+<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
+for short quotations that don't require paragraph breaks.</q> -- <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">
+<cite>MDN q page</cite></a>.</p>
+ +

Citations are styled in italic font by default. You can see this code at work in our quotations.html example.

+ +

Active learning: Who said that?

+ +

Time for another active learning example! In this example we'd like you to:

+ +
    +
  1. Turn the middle paragraph into a blockquote, which includes a cite attribute.
  2. +
  3. Turn part of the third paragraph into an inline quote, which includes a cite attribute.
  4. +
  5. Include a <cite> element for each link to say what the title of the quoted source is.
  6. +
+ +

The citation sources you need are:

+ + + +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

+ + + +

{{ EmbedLiveSample('Playable_code_2', 700, 450, "", "", "hide-codepen-jsfiddle") }}

+ +

Abbreviations

+ +

Another fairly common element you'll meet when looking around the Web is {{htmlelement("abbr")}} — this is used to wrap around an abbreviation or acronym, and provide a full expansion of the term (included inside a {{htmlattrxref("title")}} attribute.) Let's look at a couple of examples:

+ +
<p>We use <abbr title="Hypertext Markup Language">HTML</abbr> to structure our web documents.</p>
+
+<p>I think <abbr title="Reverend">Rev.</abbr> Green did it in the kitchen with the chainsaw.</p>
+ +

These will come out looking something like this (the expansion will appear in a tooltip when the term is hovered over):

+ +

We use HTML to structure our web documents.

+ +

I think Rev. Green did it in the kitchen with the chainsaw.

+ +
+

Note: There is another element, {{htmlelement("acronym")}}, which basically does the same thing as <abbr>, and was intended specifically for acronyms rather than abbreviations. This however has fallen into disuse — it wasn't supported in browsers as well as <abbr>, and has such a similar function that it was considered pointless to have both. Just use <abbr> instead.

+
+ +

Active learning: marking up an abbreviation

+ +

For this simple active learning assignment, we'd like you to simply mark up an abbreviation. You can use our sample below, or replace it with one of your own. 

+ + + +

{{ EmbedLiveSample('Playable_code_3', 700, 300, "", "", "hide-codepen-jsfiddle") }}

+ +

Marking up contact details

+ +

HTML has an element for marking up contact details — {{htmlelement("address")}}. This simply wraps around your contact details, for example:

+ +
<address>
+  <p>Chris Mills, Manchester, The Grim North, UK</p>
+</address>
+ +

One thing to remember however is that the {{htmlelement("address")}} element is meant for marking up the contact details of the person who wrote the HTML document, not any address. So the above would only be ok if Chris had written the document the markup appears on. Note that something like this would also be ok:

+ +
<address>
+  <p>Page written by <a href="../authors/chris-mills/">Chris Mills</a>.</p>
+</address>
+ +

Superscript and subscript

+ +

You will occasionally need to use superscript and subscript when marking up items like dates, chemical formulae, and mathematical equations so they have the correct meaning. The {{htmlelement("sup")}} and {{htmlelement("sub")}} elements handle this job. For example:

+ +
<p>My birthday is on the 25<sup>th</sup> of May 2001.</p>
+<p>Caffeine's chemical formula is C<sub>8</sub>H<sub>10</sub>N<sub>4</sub>O<sub>2</sub>.</p>
+<p>If x<sup>2</sup> is 9, x must equal 3 or -3.</p>
+ +

The output of this code looks like so:

+ +

My birthday is on the 25th of May 2001.

+ +

Caffeine's chemical formula is C8H10N4O2.

+ +

If x2 is 9, x must equal 3 or -3.

+ +

Representing computer code

+ +

There are a number of elements available for marking up computer code using HTML:

+ + + +

Let's look at a few examples. You should try having a play with these (try grabbing a copy of our other-semantics.html sample file):

+ +
<pre><code>var para = document.querySelector('p');
+
+para.onclick = function() {
+  alert('Owww, stop poking me!');
+}</code></pre>
+
+<p>You shouldn't use presentational elements like <code>&lt;font&gt;</code> and <code>&lt;center&gt;</code>.</p>
+
+<p>In the above JavaScript example, <var>para</var> represents a paragraph element.</p>
+
+
+<p>Select all the text with <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + <kbd>A</kbd>.</p>
+
+<pre>$ <kbd>ping mozilla.org</kbd>
+<samp>PING mozilla.org (63.245.215.20): 56 data bytes
+64 bytes from 63.245.215.20: icmp_seq=0 ttl=40 time=158.233 ms</samp></pre>
+ +

The above code will look like so:

+ +

{{ EmbedLiveSample('Representing_computer_code','100%',300, "", "", "hide-codepen-jsfiddle") }}

+ +

Marking up times and dates

+ +

HTML also provides the {{htmlelement("time")}} element for marking up times and dates in a machine-readable format. For example:

+ +
<time datetime="2016-01-20">20 January 2016</time>
+ +

Why is this useful? Well, there are many different ways that humans write down dates. The above date could be written as:

+ + + +

But these different forms cannot be easily recognised by computers — what if you wanted to automatically grab the dates of all events in a page and insert them into a calendar? The {{htmlelement("time")}} element allows you to attach an unambiguous, machine-readable time/date for this purpose.

+ +

The basic example above just provides a simple machine readable date, but there are many other options that are possible, for example:

+ +
<!-- Standard simple date -->
+<time datetime="2016-01-20">20 January 2016</time>
+<!-- Just year and month -->
+<time datetime="2016-01">January 2016</time>
+<!-- Just month and day -->
+<time datetime="01-20">20 January</time>
+<!-- Just time, hours and minutes -->
+<time datetime="19:30">19:30</time>
+<!-- You can do seconds and milliseconds too! -->
+<time datetime="19:30:01.856">19:30:01.856</time>
+<!-- Date and time -->
+<time datetime="2016-01-20T19:30">7.30pm, 20 January 2016</time>
+<!-- Date and time with timezone offset-->
+<time datetime="2016-01-20T19:30+01:00">7.30pm, 20 January 2016 is 8.30pm in France</time>
+<!-- Calling out a specific week number-->
+<time datetime="2016-W04">The fourth week of 2016</time>
+ +

Summary

+ +

That marks the end of our study of HTML text semantics. Bear in mind that what you have seen during this course is not an exhaustive list of HTML text elements — we wanted to try to cover the essentials, and some of the more common ones you will see in the wild, or at least might find interesting. To find way more HTML elements, you can take a look at our HTML element reference (the Inline text semantics section would be a great place to start.) In the next article we will look at the HTML elements you'd use to structure the different parts of an HTML document.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html b/files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html new file mode 100644 index 0000000000..502bfda4cf --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html @@ -0,0 +1,331 @@ +--- +title: Criar hiperligações +slug: Learn/HTML/Introducao_ao_HTML/Criar_hiperligacoes +tags: + - Aprender + - Guía + - HTML + - HTTP + - Hiperligações + - Principiante + - URL + - título +translation_of: Learn/HTML/Introduction_to_HTML/Creating_hyperlinks +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}
+ +

Hyperlinks are really important — they are what makes the Web a web. This article shows the syntax required to make a link, and discusses link best practices.

+ + + + + + + + + + + + +
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:To learn how to implement a hyperlink effectively, and link multiple files together.
+ + + +

Hyperlinks are one of the most exciting innovations the Web has to offer. Well, they've been a feature of the Web since the very beginning, but they are what makes the Web a Web — they allow us to link our documents to any other document (or other resource) we want to, we can also link to specific parts of documents, and we can make apps available at a simple web address (contrast this to native apps, which have to be installed and all that business.) Just about any web content can be converted to a link, so that when clicked (or otherwise activated) it will make the web browser go to another web address ({{glossary("URL")}}).

+ +
+

Note: A URL can point to HTML files, text files, images, text documents, video and audio files, and anything else that can live on the Web. If the web browser doesn't know how to display or handle the file, it will ask you if you want to open the file (in which case the duty of opening or handling the file is passed to a suitable native app on the device) or download the file (in which case you can try to deal with it later on.)

+
+ +

The BBC homepage, for example, contains a large number of links that point not only to multiple news stories, but also different areas of the site (navigation functionality), login/registration pages (user tools) and more.

+ +

frontpage of bbc.co.uk, showing many news items, and navigation menu functionality

+ + + +

A basic link is created by wrapping the text (or other content, see {{anch("Block level links")}}) you want to turn into a link inside an {{htmlelement("a")}} element, and giving it an {{htmlattrxref("href", "a")}} attribute (also known as a Hypertext Reference , or target) that will contain the web address you want the link to point to.

+ +
<p>I'm creating a link to
+<a href="https://www.mozilla.org/en-US/">the Mozilla homepage</a>.
+</p>
+ +

This gives us the following result:

+ +

I'm creating a link to the Mozilla homepage.

+ +

Adding supporting information with the title attribute

+ +

Another attribute you may want to add to your links is title; this is intended to contain supplementary useful information about the link, such as what kind of information the page contains, or things to be aware of. For example:

+ +
<p>I'm creating a link to
+<a href="https://www.mozilla.org/en-US/"
+   title="The best place to find more information about Mozilla's
+          mission and how to contribute">the Mozilla homepage</a>.
+</p>
+ +

This gives us the following result (the title will come up as a tooltip when the link is hovered over):

+ +

I'm creating a link to the Mozilla homepage.

+ +
+

Note: A link title is only revealed on mouse hover, which means that people relying on keyboard controls to navigate web pages will have difficulty accessing title information. If a title's information is truly important to the usability of page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.

+
+ + + +

Active learning time: we'd like you to create an HTML document using your local code editor (our getting started template would do just fine.)

+ + + + + +

As mentioned before, you can turn just about any content into a link, even block level elements. If you had an image you wanted to turn into a link, you could just put the image between <a></a> tags.

+ +
<a href="https://www.mozilla.org/en-US/">
+  <img src="mozilla-image.png" alt="mozilla logo that links to the mozilla homepage">
+</a>
+ +
+

Note: You'll find out a lot more about using images on the Web in a future article.

+
+ +

A quick primer on URLs and paths

+ +

To fully understand link targets, you need to understand URLs and file paths. This section gives you the information you need to achieve this.

+ +

A URL, or Uniform Resource Locator is simply a string of text that defines where something is located on the Web. For example Mozilla's English homepage is located at https://www.mozilla.org/en-US/.

+ +

URLs use paths to find files. Paths specify where in the filesystem the file you are interested in is located. Let's look at a simple example of a directory structure (see the creating-hyperlinks directory.)

+ +

A simple directory structure. The parent directory is called creating-hyperlinks and contains two files called index.html and contacts.html, and two directories called projects and pdfs, which contain an index.html and a project-brief.pdf file, respectively

+ +

The root of this directory structure is called creating-hyperlinks. When working locally with a web site, you will have one directory that the whole site goes inside. Inside the root, we have an index.html file and a contacts.html. In a real website, index.html would be our home page or landing page (a web page that serves as the entry point for a website or a particular section of a website.).

+ +

There are also two directories inside our root — pdfs and projects. These each have a single file inside them — a PDF (project-brief.pdf) and an index.html file, respectively. Note how you can quite happily have two index.html files in one project as long as they are in different locations in the filesystem. Many web sites do. The second index.html would perhaps be the main landing page for project-related information.

+ + + +
+

Note: You can combine multiple instances of these features into complex URLs, if needed, e.g. ../../../complex/path/to/my/file.html.

+
+ +

Document fragments

+ +

It is possible to link to a specific part of an HTML document (known as a document fragment), rather than just to the top of the document. To do this you first have to assign an {{htmlattrxref("id")}} attribute to the element you want to link to. It normally makes sense to link to a specific heading, so this would look something like the following:

+ +
<h2 id="Mailing_address">Mailing address</h2>
+ +

Then to link to that specific id, you'd include it at the end of the URL, preceded by a hash/pound symbol, for example:

+ +
<p>Want to write us a letter? Use our <a href="contacts.html#Mailing_address">mailing address</a>.</p>
+ +

You can even use the document fragment reference on its own to link to another part of the same document:

+ +
<p>The <a href="#Mailing_address">company mailing address</a> can be found at the bottom of this page.</p>
+ +

Absolute versus relative URLs

+ +

Two terms you'll come across on the Web are absolute URL and relative URL:

+ +

absolute URL: Points to a location defined by its absolute location on the web, including {{glossary("protocol")}} and {{glossary("domain name")}}. So for example, if an index.html page is uploaded to a directory called projects that sits inside the root of a web server, and the web site's domain is http://www.example.com, the page would be available at http://www.example.com/projects/index.html (or even just http://www.example.com/projects/, as most web servers just look for a landing page such as index.html to load if it is not specified in the URL.)

+ +

An absolute URL will always point to the same location, no matter where it is used.

+ +

relative URL: Points to a location that is relative to the file you are linking from, more like what we looked at in the previous section. For example, if we wanted to link from our example file at http://www.example.com/projects/index.html to a PDF file in the same directory, the URL would just be the filename — e.g. project-brief.pdf — no extra information needed. If the PDF was available in a subdirectory inside projects called pdfs, the relative link would be pdfs/project-brief.pdf (the equivalent absolute URL would be http://www.example.com/projects/pdfs/project-brief.pdf.)

+ +

A relative URL will point to different places depending on where the file it is used inside is located — for example if we moved our index.html file out of the projects directory and into the root of the web site (the top level, not in any directories), the pdfs/project-brief.pdf relative URL link inside it would now point to a file located at http://www.example.com/pdfs/project-brief.pdf, not a file located at http://www.example.com/projects/pdfs/project-brief.pdf.

+ +

Of course, the location of the project-brief.pdf file and pdfs folder won't suddenly change because you moved the index.html file — this would make your link point to the wrong place, so it wouldn't work if clicked on. You need to be careful!

+ + + +

There are some best practices to follow when writing links. Let's look at these now.

+ + + + + +

It's easy to throw links up on your page. That's not enough. We need to make our links accessible to all readers, regardless of their current context and which tools they prefer. For example:

+ + + +

Let's look at a specific example:

+ +

Good link text: Download Firefox

+ +
<p><a href="https://firefox.com/">
+  Download Firefox
+</a></p>
+ +

Bad link text: Click here to download Firefox

+ +
<p><a href="https://firefox.com/">
+  Click here
+</a>
+to download Firefox</p>
+
+ +

Other tips:

+ + + + + +

From the description above, you might think that it is a good idea to just use absolute links all the time; after all, they don't break when a page is moved like relative links. However, you should use relative links wherever possible when linking to other locations within the same website (when linking to another website, you will need to use an absolute link):

+ + + +

Linking to non-HTML resources — leave clear signposts

+ +

When linking to a resource that will be downloaded (like a PDF or Word document) or streamed (like video or audio) or has another potentially unexpected effect (opens a popup window, or loads a Flash movie), you should add clear wording to reduce any confusion. It can be quite annoying for example:

+ + + +

Let's look at some examples, to see what kind of text can be used here:

+ +
<p><a href="http://www.example.com/large-report.pdf">
+  Download the sales report (PDF, 10MB)
+</a></p>
+
+<p><a href="http://www.example.com/video-stream/" target="_blank">
+  Watch the video (stream opens in separate tab, HD quality)
+</a></p>
+
+<p><a href="http://www.example.com/car-game">
+  Play the car game (requires Flash)
+</a></p>
+ +

Use the download attribute when linking to a download

+ +

When you are linking to a resource that is to be downloaded rather than opened in the browser, you can use the download attribute to provide a default save filename. Here's an example with a download link to the latest Windows version of Firefox:

+ +
<a href="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=en-US"
+   download="firefox-latest-64bit-installer.exe">
+  Download Latest Firefox for Windows (64-bit) (English, US)
+</a>
+ +

Active learning: creating a navigation menu

+ +

For this exercise, we'd like you to link some pages together with a navigation menu to create a multi-page website. This is one common way in which a website is created — the same page structure is used on every page, including the same navigation menu, so when links are clicked it gives the impression that you are staying in the same place, and different content is being brought up.

+ +

You'll need to make local copies of the following four pages, all in the same directory (see also the navigation-menu-start directory for a full file listing):

+ + + +

You should:

+ +
    +
  1. Add an unordered list in the indicated place on one page, containing the names of the pages to link to. A navigation menu is usually just a list of links, so this is semantically ok.
  2. +
  3. Turn each page name into a link to that page.
  4. +
  5. Copy the navigation menu across to each page.
  6. +
  7. On each page, remove just the link to that same page — it is confusing and pointless for a page to include a link to itself, and the lack of a link acts a good visual reminder of what page you are currently on.
  8. +
+ +

The finished example should end up looking something like this:

+ +

An example of a simple HTML navigation menu, with home, pictures, projects, and social menu items

+ +
+

Note: If you get stuck, or are not sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer.

+
+ + + +

It is possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. This is done using the {{HTMLElement("a")}} element and the mailto: URL scheme.

+ +

In its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. For example:

+ +
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>
+
+ +

This results in a link that looks like this: Send email to nowhere.

+ +

In fact, the email address is even optional. If you leave it out (that is, your {{htmlattrxref("href", "a")}} is simply "mailto:"), a new outgoing email window will be opened by the user's mail client that has no destination address specified yet. This is often useful as "Share" links that users can click to send an email to an address of their choosing.

+ +

Specifying details

+ +

In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term.

+ +

Here's an example that includes a cc, bcc, subject and body:

+ +
<a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email">
+  Send mail with cc, bcc, subject and body
+</a>
+ +
+

Note: The values of each field must be URL-encoded, that is with non-printing characters (invisible characters like tabs, carriage returns, and page breaks) and spaces percent-escaped. Also note the use of the question mark (?) to separate the main URL from the field values, and ampersands (&) to separate each field in the mailto: URL. This is standard URL query notation. Read The GET method to understand what URL query notation is more comonly used for.

+
+ +

Here are a few other sample mailto URLs:

+ + + +

Summary

+ +

That's it for links, for now anyway! You'll return to links later on in the course when you start to look at styling them. Next up for HTML, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful — Advanced text formatting is your next stop.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}

+ +

In this module

+ + diff --git a/files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html b/files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html new file mode 100644 index 0000000000..9515ff4f37 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html @@ -0,0 +1,186 @@ +--- +title: Depurar HTML +slug: Learn/HTML/Introducao_ao_HTML/Depurar_HTML +tags: + - Depuração + - Erro + - Guía + - HTML + - Principiante + - Validação +translation_of: Learn/HTML/Introduction_to_HTML/Debugging_HTML +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
+ +

Writing HTML is fine, but what if something goes wrong, and you can't work out where the error in the code is? This article will introduce you to some tools that can help you find and fix errors in HTML.

+ + + + + + + + + + + + +
Prerequisites:HTML familiarity, as covered in for example Getting started with HTML, HTML text fundamentals, and Creating hyperlinks.
Objective:Learn the basics of using debugging tools to find problems in HTML.
+ +

Debugging isn't scary

+ +

When writing code of some kind, everything is usually fine, until that dreaded moment when an error occurs — you've done something wrong, so your code doesn't work — either not at all, or not quite how you wanted it to. For example, the following shows an error reported when trying to {{glossary("compile")}} a simple program written in the Rust language.

+ +

A console window showing the result of trying to compile a rust program with a missing quote around a string in a print statement. The error message reported is error: unterminated double quote string.Here, the error message is relatively easy to understand — "unterminated double quote string". If you look at the listing, you can probably see how println!(Hello, world!"); might logically be missing a double quote. However, error messages can quickly get more complicated and less easy to interpret as programs get bigger, and even simple cases can look a little intimidating to someone who doesn't know anything about Rust.

+ +

Debugging doesn't have to be scary though —  the key to being comfortable with writing and debugging any programming language or code is familiarity with both the language and the tools.

+ +

HTML and debugging

+ +

HTML is not as complicated to understand as Rust. HTML is not compiled into a different form before the browser parses it and shows the result (it is interpreted, not compiled). And HTML's {{glossary("element")}} syntax is arguably a lot easier to understand than a "real programming language" like Rust, {{glossary("JavaScript")}}, or {{glossary("Python")}}. The way that browsers parse HTML is a lot more permissive than how programming languages are run, which is both a good and a bad thing.

+ +

Permissive code

+ +

So what do we mean by permissive? Well, generally when you do something wrong in code, there are two main types of error that you'll come across:

+ + + +

HTML itself doesn't suffer from syntax errors because browsers parse it permissively, meaning that the page still displays even if there are syntax errors. Browsers have built-in rules to state how to interpret incorrectly written markup, so you'll get something running, even if it is not what you expected. This, of course, can still be a problem!

+ +
+

Note: HTML is parsed permissively because when the web was first created, it was decided that allowing people to get their content published was more important than making sure the syntax was absolutely correct. The web would probably not be as popular as it is today, if it had been more strict from the very beginning.

+
+ +

Active learning: Studying permissive code

+ +

It's time to study the permissive nature of HTML code.

+ +
    +
  1. First, download our debug-example demo and save it locally. This demo is deliberately written to have some errors in it for us to explore (the HTML markup is said to be badly-formed, as opposed to well-formed).
  2. +
  3. Next, open it in a browser. You will see something like this:A simple HTML document with a title of HTML debugging examples, and some information about common HTML errors, such as unclosed elements, badly nested elements, and unclosed attributes.
  4. +
  5. This immediately doesn't look great; let's look at the source code to see if we can work out why (only the body contents are shown): +
    <h1>HTML debugging examples</h1>
    +
    +<p>What causes errors in HTML?
    +
    +<ul>
    +  <li>Unclosed elements: If an element is <strong>not closed properly,
    +      then its effect can spread to areas you didn't intend
    +
    +  <li>Badly nested elements: Nesting elements properly is also very important
    +      for code behaving correctly. <strong>strong <em>strong emphasised?</strong>
    +      what is this?</em>
    +
    +  <li>Unclosed attributes: Another common source of HTML problems. Let's
    +      look at an example: <a href="https://www.mozilla.org/>link to Mozilla
    +      homepage</a>
    +</ul>
    +
  6. +
  7. Let's review the problems: +
      +
    • The {{htmlelement("p","paragraph")}} and {{htmlelement("li","list item")}} elements have no closing tags. Looking at the image above, this doesn't seem to have affected the markup rendering too badly, as it is easy to infer where one element should end and another should begin.
    • +
    • The first {{htmlelement("strong")}} element has no closing tag. This is a bit more problematic, as it isn't easy to tell where the element is supposed to end. In fact, the whole of the rest of the text has been strongly emphasised.
    • +
    • This section is badly nested: <strong>strong <em>strong emphasised?</strong> what is this?</em>. It is not easy to tell how this has been interpreted because of the previous problem.
    • +
    • The {{htmlattrxref("href","a")}} attribute value has a missing closing double quote. This seems to have caused the biggest problem — the link has not rendered at all.
    • +
    +
  8. +
  9. Now let's look at the markup the browser has rendered, as opposed to the markup in the source code. To do this, we can use the browser developer tools. If you are not familiar with how to use your browser's developer tools, take a few minutes to review Discover browser developer tools.
  10. +
  11. In the DOM inspector, you can see what the rendered markup looks like: The HTML inspector in Firefox, with our example's paragraph highlighted, showing the text "What causes errors in HTML?" Here you can see that the paragraph element has been closed by the browser.
  12. +
  13. Using the DOM inspector, let's explore our code in detail to see how the browser has tried to fix our HTML errors (we did the review in Firefox; other modern browsers should give the same result): +
      +
    • The paragraphs and list items have been given closing tags.
    • +
    • It isn't clear where the first <strong> element should be closed, so the browser has wrapped each separate block of text with its own strong tag, right down to the bottom of the document!
    • +
    • The  incorrect nesting has been fixed by the browser like this: +
      <strong>strong
      +  <em>strong emphasised?</em>
      +</strong>
      +<em> what is this?</em>
      +
    • +
    • The link with the missing double quote has been deleted altogether. The last list item looks like this: +
      <li>
      +  <strong>Unclosed attributes: Another common source of HTML problems.
      +  Let's look at an example: </strong>
      +</li>
      +
    • +
    +
  14. +
+ +

HTML validation

+ +

So you can see from the above example that you really want to make sure your HTML is well-formed! But how? In a small example like the one seen above, it is easy to search through the lines and find the errors, but what about a huge, complex HTML document?

+ +

The best strategy is to start by running your HTML page through the Markup Validation Service — created and maintained by the W3C, the organization that looks after the specifications that define HTML, CSS, and other web technologies. This webpage takes an HTML document as an input, goes through it, and gives you a report to tell you what is wrong with your HTML.

+ +

The HTML validator homepage

+ +

To specify the HTML to validate, you can give it a web address, upload an HTML file, or directly input some HTML code.

+ +

Active learning: Validating an HTML document

+ +

Let's try this with our sample document.

+ +
    +
  1. First, load up the Markup Validation Service in one browser tab, if it isn't already.
  2. +
  3. Switch to the Validate by Direct Input tab.
  4. +
  5. Copy all the sample document's code (not just the body) and paste it into the large text area shown in the Markup Validation Service.
  6. +
  7. Press the Check button.
  8. +
+ +

This should give you a list of errors and other information.

+ +

A list of of HTML validation results from the W3C markup validation service

+ +

Interpreting the error messages

+ +

The error messages are usually helpful, but sometimes they are not so helpful; with a bit of practice you can work out how to interpret these to fix your code. Let's go through the error messages and what they mean. You'll see that each message comes with a line and column number to help you to locate the error easily.

+ + + +

If you can't work out what every error message means, don't worry about it — a good idea is to try fixing a few errors at a time. Then try revalidating your HTML to show what errors are left. Sometimes fixing an earlier error will also get rid of other error messages — several errors can often be caused by a single problem, in a domino effect.

+ +

You will know when all your errors are fixed when you see the following banner in your output:

+ +

Banner that reads "The document validates according to the specified schema(s) and to additional constraints checked by the validator."

+ +

Summary

+ +

So there we have it, an introduction to debugging HTML, which should give you some useful skills to count on when you start to debug CSS, JavaScript, and other types of code later on in your career. This also marks the end of the Introduction to HTML module learning articles — now you can go on to testing yourself with our assessments: the first one is linked below.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html b/files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html new file mode 100644 index 0000000000..059f26a497 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html @@ -0,0 +1,292 @@ +--- +title: "Estrutura do\_documento e do website" +slug: Learn/HTML/Introducao_ao_HTML/Estrutura_documento_website +tags: + - Guía + - HTML + - Layout + - Principiante + - pagina + - semántica +translation_of: Learn/HTML/Introduction_to_HTML/Document_and_website_structure +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}
+ +

In addition to defining individual parts of your page (such as "a paragraph" or "an image"), {{glossary("HTML")}} also boasts a number of block level elements used to define areas of your website (such as "the header", "the navigation menu", "the main content column"). This article looks into how to plan a basic website structure, and write the HTML to represent this structure.

+ + + + + + + + + + + + +
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals. How hyperlinks work, as covered in Creating hyperlinks.
Objective:Learn how to structure your document using semantic tags, and how to work out the structure of a simple website.
+ +

Basic sections of a document

+ +

Webpages can and will look pretty different from one another, but they all tend to share similar standard components, unless the page is displaying a fullscreen video or game, is part of some kind of art project, or is just badly structured:

+ +
+
header
+
Usually a big strip across the top with a big heading and/or logo. This is where the main common information about a website usually stays from one webpage to another.
+
navigation bar
+
Links to the site's main sections; usually represented by menu buttons, links, or tabs. Like the header, this content usually remains consistent from one webpage to another — having an inconsistent navigation on your website will just lead to confused, frustrated users. Many web designers consider the navigation bar to be part of the header rather than a individual component, but that's not a requirement; in fact some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate.
+
main content
+
A big area in the center that contains most of the unique content of a given webpage, for example the video you want to watch, or the main story you're reading, or the map you want to view, or the news headlines, etc. This is the one part of the website that definitely will vary from page to page!
+
sidebar
+
Some peripheral info, links, quotes, ads, etc. Usually this is contextual to what is contained in the main content (for example on a news article page, the sidebar might contain the author's bio, or links to related articles) but there are also cases where you'll find some recurring elements like a secondary navigation system.
+
footer
+
A strip across the bottom of the page that generally contains fine print, copyright notices, or contact info. It's a place to put common information (like the header) but usually that information is not critical or secondary to the website itself. The footer is also sometimes used for {{Glossary("SEO")}} purposes, by providing links for quick access to popular content.
+
+ +

A "typical website" could be laid out something like this:

+ +

a simple website structure example featuring a main heading, navigation menu, main content, side bar, and footer.

+ +

HTML for structuring content

+ +

The simple example shown above isn't pretty, but it is perfectly ok for illustrating a typical website layout example. Some websites have more columns, some are way more complex, but you get the idea. With the right CSS, you could use pretty much any elements to wrap around the different sections and get it looking how you wanted, but as discussed before, we need to respect semantics, and use the right element for the right job.

+ +

This is because visuals don't tell the whole story. We use color and font size to draw sighted users' attention to the most useful parts of the content, like the navigation menu and related links, but what about visually impaired people for example, who might not find concepts like "pink" and "large font" very useful?

+ +
+

Note: Colorblind people represent around 4% of the world population or, to put it another way, approximately 1 in every 12 men and 1 in every 200 women are colorblind. Blind and visually impaired people represent roughly 4-5% of the world population (in 2012 there were 285 million such people in the world, while the total population was around 7 billion).

+
+ +

In your HTML code, you can mark up sections of content based on their functionality — you can use elements that represent the sections of content described above unambiguously, and assistive technologies like screenreaders can recognise those elements and help with tasks like "find the main navigation", or "find the main content." As we mentioned earlier in the course, there are a number of consequences of not using the right element structure and semantics for the right job.

+ +

To implement such semantic mark up, HTML provides dedicated tags that you can use to represent such sections, for example:

+ + + +

Active learning: exploring the code for our example

+ +

Our example seen above is represented by the following code (you can also find the example in our GitHub repository). We'd like you to look at the example above, and then look over the listing below to see what parts make up what section of the visual.

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+
+    <title>My page title</title>
+    <link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Sonsie+One" rel="stylesheet" type="text/css">
+    <link rel="stylesheet" href="style.css">
+
+    <!-- the below three lines are a fix to get HTML5 semantic elements working in old versions of Internet Explorer-->
+    <!--[if lt IE 9]>
+      <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
+    <![endif]-->
+  </head>
+
+  <body>
+    <!-- Here is our main header that is used across all the pages of our website -->
+
+    <header>
+      <h1>Header</h1>
+    </header>
+
+    <nav>
+      <ul>
+        <li><a href="#">Home</a></li>
+        <li><a href="#">Our team</a></li>
+        <li><a href="#">Projects</a></li>
+        <li><a href="#">Contact</a></li>
+      </ul>
+
+       <!-- A Search form is another commmon non-linear way to navigate through a website. -->
+
+       <form>
+         <input type="search" name="q" placeholder="Search query">
+         <input type="submit" value="Go!">
+       </form>
+     </nav>
+
+    <!-- Here is our page's main content -->
+    <main>
+
+      <!-- It contains an article -->
+      <article>
+        <h2>Article heading</h2>
+
+        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Donec a diam lectus. Set sit amet ipsum mauris. Maecenas congue ligula as quam viverra nec consectetur ant hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur.</p>
+
+        <h3>Subsection</h3>
+
+        <p>Donec ut librero sed accu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor.</p>
+
+        <p>Pelientesque auctor nisi id magna consequat sagittis. Curabitur dapibus, enim sit amet elit pharetra tincidunt feugiat nist imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros.</p>
+
+        <h3>Another subsection</h3>
+
+        <p>Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum soclis natoque penatibus et manis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p>
+
+        <p>Vivamus fermentum semper porta. Nunc diam velit, adipscing ut tristique vitae sagittis vel odio. Maecenas convallis ullamcorper ultricied. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, is fringille sem nunc vet mi.</p>
+      </article>
+
+      <!-- the aside content can also be nested within the main content -->
+      <aside>
+        <h2>Related</h2>
+
+        <ul>
+          <li><a href="#">Oh I do like to be beside the seaside</a></li>
+          <li><a href="#">Oh I do like to be beside the sea</a></li>
+          <li><a href="#">Although in the North of England</a></li>
+          <li><a href="#">It never stops raining</a></li>
+          <li><a href="#">Oh well...</a></li>
+        </ul>
+      </aside>
+
+    </main>
+
+    <!-- And here is our main footer that is used across all the pages of our website -->
+
+    <footer>
+      <p>©Copyright 2050 by nobody. All rights reversed.</p>
+    </footer>
+
+  </body>
+</html>
+ +

Take some time to look over the code and understand it — the comments inside the code should also help you to understand it. We aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound HTML structure, and then laying it out with CSS. We'll wait for this until you start to study CSS layout as part of the CSS topic.

+ +

HTML layout elements in more detail

+ +

It's good to understand the overall meaning of all the HTML sectioning elements in detail — this is something you'll work on gradually as you start to get more experience with web development. You can find a lot of detail by reading our HTML element reference. For now, these are the main definitions that you should try to understand:

+ + + +

Non-semantic wrappers

+ +

Sometimes you'll come across a situation where you can't find an ideal semantic element to group some items together or wrap some content. Sometimes you might want to just group a set of elements together to affect them all as a single entity with some {{glossary("CSS")}} or {{glossary("JavaScript")}}. For cases like these, HTML provides the {{HTMLElement("div")}} and {{HTMLElement("span")}} elements. You should use these preferably with a suitable {{htmlattrxref('class')}} attribute, to provide some kind of label for them so they can be easily targeted.

+ +

{{HTMLElement("span")}} is an inline non-semantic element, which you should only use if you can't think of a better semantic text element to wrap your content, or don't want to add any specific meaning. For example:

+ +
<p>The King walked drunkenly back to his room at 01:00, the beer doing nothing to aid
+him as he staggered through the door <span class="editor-note">[Editor's note: At this point in the
+play, the lights should be down low]</span>.</p>
+ +

In this case, the editor's note is supposed to merely provide extra direction for the director of the play; it is not supposed to have extra semantic meaning. For sighted users, CSS would perhaps be used to distance the note slightly from the main text.

+ +

{{HTMLElement("div")}} is a block level non-semantic element, which you should only use if you can't think of a better semantic block element to use, or don't want to add any specific meaning. For example, imagine a shopping cart widget that you could choose to pull up at any point during your time on an e-commerce site:

+ +
<div class="shopping-cart">
+  <h2>Shopping cart</h2>
+  <ul>
+    <li>
+      <p><a href=""><strong>Silver earrings</strong></a>: $99.95.</p>
+      <img src="../products/3333-0985/thumb.png" alt="Silver earrings">
+    </li>
+    <li>
+      ...
+    </li>
+  </ul>
+  <p>Total cost: $237.89</p>
+</div>
+ +

This isn't really an <aside>, as it doesn't necessarily relate to the main content of the page (you want it viewable from anywhere). It doesn't even particularly warrant using a  <section>, as it isn't part of the main content of the page. So a <div> is fine in this case. We've included a heading as a signpost to aid screenreader users in finding it.

+ +
+

Warning: Divs are so convenient to use that it's easy to use them too much. As they carry no semantic value, they just clutter your HTML code. Take care to use them only when there is no better semantic solution and try to reduce their usage to the minimum otherwise you'll have a hard time updating and maintaining your documents.

+
+ +

Line breaks and horizontal rules

+ +

Two elements that you'll use occasionally and will want to know about are {{htmlelement("br")}} and {{htmlelement("hr")}}:

+ +

<br> creates a line break in a paragraph; it is the only way to force a rigid structure in a situation where you want a series of fixed short lines, such as in a postal address or a poem. For example:

+ +
<p>There once was a man named O'Dell<br>
+Who loved to write HTML<br>
+But his structure was bad, his semantics were sad<br>
+and his markup didn't read very well.</p>
+ +

Without the <br> elements, the paragraph would just be rendered in one long line (as we said earlier in the course, HTML ignores most whitespace); with them in the code, the markup renders like this:

+ +

There once was a man named O'Dell
+ Who loved to write HTML
+ But his structure was bad, his semantics were sad
+ and his markup didn't read very well.

+ +

<hr> elements create a horizontal rule in the document that denotes a thematic change in the text (such as a change in topic or scene). Visually it just looks like a horizontal line. As an example:

+ +
<p>Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.</p>
+<hr>
+<p>Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.</p>
+ +

Would render like this:

+ +

Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.

+ +
+

Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.

+ +

Planning a simple website

+ +

Once you've planned out the content of a simple webpage, the next logical step is to try to work out what content you want to put on a whole website, what pages you need, and how they should be arranged and link to one another for the best possible user experience. This is called {{glossary("Information architecture")}}. In a large, complex website, a lot of planning can go into this process, but for a simple website of a few pages this can be fairly simple, and fun!

+ +
    +
  1. Bear in mind that you'll have a few elements common to most (if not all) pages — such as the navigation menu, and the footer content. If your site is for a business, for example, it's a good idea to have your contact information available in the footer on each page. Note down what you want to have common to every page.the common features of the travel site to go on every page: title and logo, contact, copyright, terms and conditions, language chooser, accessibility policy
  2. +
  3. Next, draw a rough sketch of what you might want the structure of each page to look like (it might look like our simple website above). Note what each block is going to be.A simple diagram of a sample site structure, with a header, main content area, two optional sidebars, and footer
  4. +
  5. Now, brainstorm all the other (not common to every page) content you want to have on your website — write a big list down.A long list of all the features that we could put on our travel site, from searching, to special offers and country-specific info
  6. +
  7. Next, try to sort all these content items into groups, to give you an idea of what parts might live together on different pages. This is very similar to a technique called {{glossary("Card sorting")}}.The items that should appear on a holiday site sorted into 5 categories: Search, Specials, Country-specific info, Search results, and Buy things
  8. +
  9. Now try to sketch a rough sitemap — have a bubble for each page on your site, and draw lines to show the typical workflow between pages. The homepage will probably be in the center, and link to most if not all of the others; most of the pages in a small site should be available from the main navigation, although there are exceptions. You might also want to include notes about how things might be presented.A map of the site showing the homepage, country page, search results, specials page, checkout, and buy page
  10. +
+ +

Active learning: create your own sitemap

+ +

Try carrying out the above exercise for a website of your own creation. What would you like to make a site about?

+ +
+

Note: Save your work somewhere; you might need it later on.

+
+ +

Summary

+ +

At this point you should have a better idea about how to structure a web page/site. In the last article of this module, we'll study how to debug HTML.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/getting_started/index.html b/files/pt-pt/learn/html/introduction_to_html/getting_started/index.html new file mode 100644 index 0000000000..981b23e556 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/getting_started/index.html @@ -0,0 +1,612 @@ +--- +title: Começar com HTML +slug: Learn/HTML/Introducao_ao_HTML/Iniciacao_HTML +tags: + - Comentário + - Elemento + - Guía + - HTML + - Principiante + - atributo + - espaço em branco + - referência de entidade +translation_of: Learn/HTML/Introduction_to_HTML/Getting_started +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/HTML/Introducao_ao_HTML/Os_metadados_de_head_em_HTML", "Learn/HTML/Introducao_ao_HTML")}}
+ +

Neste artigo nós iremos abranger os básicos absolutos de HTML, para o iniciar — nós definimos os elementos, atributos, e todos os outros termos importantes que já poderá ter ouvido, e onde os incorporar na linguagem. Nós também mostramos como é que o elemento de HTML é estruturado, como é que uma página HTML é estruturada, e explicar outras funcionalidades de linguagem básica importantes. E nós iremos algumas demonstrações de algum HTML, para o motivar!

+ + + + + + + + + + + + +
Pré-requisitos:Basic computer literacy, basic software installed, and basic knowledge of working with files.
Objetivo:To gain basic familiarity with the HTML language, and get some practice writing a few HTML elements.
+ +

O que é HTML?

+ +

{{glossary("HTML")}} (Linguagem de Marcação de Hipertexto) não é uma linguagem de programação; é uma linguagem de marcação utilizada para comunicar ao seu navegador como estruturar as páginas da Web que visita. Este pode ser tão complicado ou tão simples como o programador da Web o desejar. HTML consiste em uma série de  {{glossary("Element", "elementos")}}, que utiliza para incluir, ou marcar diferentes partes do conteúdo para que este apareça ou atue de uma determinada maneira. A inclusão de {{glossary("Tag", "etiquetas")}} pode tornar uma parte do conteúdo em uma hiperligação para interligar com outra página na Web, colocar as palavras em itálico, e assim por diante. Por exemplo, siga a seguinte linha de conteúdo:

+ +
My cat is very grumpy
+ +

Se quisermos que a linha esteja demarcada, podemos especificar que é um parágrafo, encerrando-a num elemento com tag de parágrafo ({{htmlelement("p")}}) :

+ +
<p>My cat is very grumpy</p>
+ +

Anatomia de um elemento HTML

+ +

Vamos explorar o nosso elemento parágrafo um pouco mais:

+ +

+ +

As partes principais do nosso elemento são:

+ +
    +
  1. A tag de abertura: Isto consiste no nome do elemento (neste caso, p), envolta por colchetes angulares de abertura ( < ) e fecho ( > ). Isto especifica onde o elemento começa, ou onde começa a ter efeito - neste caso, onde está o início do parágrafo.
  2. +
  3. A tag de fecho: Isto é o mesmo que a tag de abertura, só que inclui um traço ( \ ) antes do nome do elemento. Isto indica onde é que o elemento acaba - neste caso, onde é o fim do parágrafo. Esquecer-se de incluir uma tag de fecho é um erro comum de principiante e pode levar a resultados estranhos.
  4. +
  5. O conteúdo: É o conteúdo do elemento, que neste caso é só texto.
  6. +
  7. O elemento: A tag de abertura mais a tag de fecho mais o conteúdo é igual ao elemento.
  8. +
+ +

Aprendizagem ativa: criar o seu primeiro HTML

+ +

Edit the line below in the Input area by wrapping it with the tags <em> and </em> (put <em> before it to open the element, and </em> after it, to close the element) — this should give the line italic emphasis! You'll be able to see your changes update live in the Output area.

+ +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 300) }}

+ +

Nesting elements

+ +

You can put elements inside other elements too — this is called nesting. If we wanted to state that our cat is very grumpy, we could wrap the word "very" in a {{htmlelement("strong")}} element, which means that the word is to be strongly emphasized:

+ +
<p>My cat is <strong>very</strong> grumpy.</p>
+ +

You do however need to make sure that your elements are properly nested: in the example above we opened the p element first, then the strong element, therefore we have to close the strong element first, then the p. The following is incorrect:

+ +
<p>My cat is <strong>very grumpy.</p></strong>
+ +

The elements have to open and close correctly so they are clearly inside or outside one another. If they overlap like above, then your web browser will try to make a best guess at what you were trying to say, and you may well get unexpected results. So don't do it!

+ +

Block versus inline elements

+ +

There are two important categories of elements in HTML, which you should know about — block-level elements and inline elements.

+ + + +

Take the following example:

+ +
<em>first</em><em>second</em><em>third</em>
+
+<p>fourth</p><p>fifth</p><p>sixth</p>
+
+ +

{{htmlelement("em")}} is an inline element, so as you can see below, the first three elements sit on the same line as one another with no space in between. On the other hand, {{htmlelement("p")}} is a block-level element, so each element appears on a new line, with space above and below each (the spacing is due to default CSS styling that the browser applies to paragraphs).

+ +

{{ EmbedLiveSample('Block_versus_inline_elements', 700, 200) }}

+ +
+

Nota: HTML5 redefined the element categories in HTML5: see Element content categories. While these definitions are more accurate and less ambiguous than the ones that went before, they are a lot more complicated to understand than "block" and "inline", so we will stick with these throughout this topic.

+
+ +
+

Nota: You can find useful reference pages that include lists of block and inline elements — see Block-level elements and Inline elements.

+
+ +

Elementos vazios

+ +

Not all elements follow the above pattern of opening tag, content, closing tag. Some elements consist only of a single tag, which is usually used to insert/embed something in the document at the place it is included. For example, the {{htmlelement("img")}} element embeds an image file onto a page in the position it is included in:

+ +
<img src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png">
+ +

This would output the following on your page:

+ +

{{ EmbedLiveSample('Empty_elements', 700, 300) }}

+ +
+

Nota: Empty elements are also sometimes called void elements.

+
+ +

Atributos

+ +

Elements can also have attributes, which look like this:

+ +

&lt;p class="editor-note">My cat is very grumpy&lt;/p>

+ +

Attributes contain extra information about the element which you don't want to appear in the actual content. In this case, the class attribute allows you to give the element an identifying name that can be later used to target the element with style information and other things.

+ +

An attribute should have:

+ +
    +
  1. A space between it and the element name (or the previous attribute, if the element already has one or more attributes.)
  2. +
  3. The attribute name, followed by an equals sign.
  4. +
  5. An attribute value, with opening and closing quote marks wrapped around it.
  6. +
+ +

Aprendizagem ativa: Adicionar atributos a um elemento

+ +

Another example of an element is {{htmlelement("a")}} — this stands for anchor and will make the piece of text it wraps around into a hyperlink. This can take a number of attributes, but several are as follows:

+ + + +

Edit the line below in the Input area to turn it into a link to your favourite website. First, add the <a> element. Second, add the href attribute and the title attribute. Lastly, specify target attribute to open the link in the new tab. You'll be able to see your changes update live in the Output area. You should see a link that when hovered over displays the title attribute's content, and when clicked navigates to the web address in the href element. Remember that you need to include a space between the element name, and each attribute.

+ +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

+ + + +

{{ EmbedLiveSample('Playable_code2', 700, 300) }}

+ +

Atributos de booliano

+ +

You'll sometimes see attributes written without values — this is perfectly allowed. These are called boolean attributes, and they can only have one value, which is generally the same as the attribute name. As an example, take the {{htmlattrxref("disabled", "input")}} attribute, which you can assign to form input elements if you want them to be disabled (greyed out) so the user can't enter any data in them.

+ +
<input type="text" disabled="disabled">
+ +

As shorthand, it is perfectly allowable to write this as follows (we've also included a non-disabled form input element for reference, to give you more of an idea what is going on):

+ +
<input type="text" disabled>
+
+<input type="text">
+
+ +

Both will give you an output as follows:

+ +

{{ EmbedLiveSample('Boolean_attributes', 700, 100) }}

+ +

Omitir aspas em volta de valores de atributo

+ +

When you look around the World Wide Web, you'll come across all kind of strange markup styles, including attribute values without quotes. This is allowable in certain circumstances, but will break your markup in others. For example, if we revisit our link example from earlier, we could write a basic version with only the href attribute, like this:

+ +
<a href=https://www.mozilla.org/>favourite website</a>
+ +

However, as soon as we add the title attribute in this style, things will go wrong:

+ +
<a href=https://www.mozilla.org/ title=The Mozilla homepage>favourite website</a>
+ +

At this point the browser will misinterpret your markup, thinking that the title attribute is actually three attributes — a title attribute with the value "The", and two boolean attributes, Mozilla and homepage. This is obviously not what was intended, and will cause errors or unexpected behaviour in the code, as seen in the live example below. Try hovering over the link to see what the title text is!

+ +

{{ EmbedLiveSample('Omitting_quotes_around_attribute_values', 700, 100) }}

+ +

Our advice is to always include the attribute quotes — it avoids such problems, and results in more readable code too.

+ +

Aspas simples ou duplas?

+ +

In this article you'll notice that the attributes are all wrapped in double quotes. You might however see single quotes in some people's HTML. This is purely a matter of style, and you can feel free to choose which one you prefer. Both the following lines are equivalent:

+ +
<a href="http://www.example.com">A link to my example.</a>
+
+<a href='http://www.example.com'>A link to my example.</a>
+ +

You should however make sure you don't mix them together. The following will go wrong!

+ +
<a href="http://www.example.com'>A link to my example.</a>
+ +

If you've used one type of quote in your HTML, you can include the other type of quote without causing any problems:

+ +
<a href="http://www.example.com" title="Isn't this fun?">A link to my example.</a>
+ +

However if you want to include a quote within the quotes where both the quotes are of the same type(single quote or double quote), you'll have to use HTML entities for the quotes.

+ +

Anatomia de uma documento HTML

+ +

That wraps up the basics of individual HTML elements, but they aren't very useful on their own. Now we'll look at how individual elements are combined to form an entire HTML page:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My test page</title>
+  </head>
+  <body>
+    <p>This is my page</p>
+  </body>
+</html>
+ +

Here we have:

+ +
    +
  1. <!DOCTYPE html>: The doctype. In the mists of time, when HTML was young (about 1991/2), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML, which could mean automatic error checking and other useful things. They used to look something like this: + +
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    + However, these days no one really cares about them, and they are really just a historical artifact that needs to be included for everything to work right. <!DOCTYPE html> is the shortest string of characters that counts as a valid doctype; that's all you really need to know.
  2. +
  3. <html></html>: The {{htmlelement("html")}} element. This element wraps all the content on the entire page, and is sometimes known as the root element.
  4. +
  5. <head></head>: The {{htmlelement("head")}} element. This element acts as a container for all the stuff you want to include on the HTML page that isn't the content you are showing to your page's viewers. This includes things like keywords and a page description that you want to appear in search results, CSS to style our content, character set declarations, and more. You'll learn more about this in the next article in the series.
  6. +
  7. <meta charset="utf-8">: This element sets the character set your document should use to UTF-8, which includes most characters from the vast majority of human written languages. Essentially it can now handle any textual content you might put on it. There is no reason not to set this, and it can help avoid some problems later on.
  8. +
  9. <title></title>: The {{htmlelement("title")}} element. This sets the title of your page, which is the title that appears in the browser tab the page is loaded in, and is used to describe the page when you bookmark/favourite it.
  10. +
  11. <body></body>: The {{htmlelement("body")}} element. This contains all the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks, or whatever else.
  12. +
+ +

Aprendizagem ativa: Adicionar alguns recursos a um documento HTML

+ +

If you want to experiment with writing some HTML on your local computer, you can:

+ +
    +
  1. Copy the HTML page example listed above.
  2. +
  3. Create a new file in your text editor.
  4. +
  5. Paste the code into the new text file.
  6. +
  7. Save the file as index.html.
  8. +
+ +
+

Nota: You can also find this basic HTML template on the MDN Learning Area Github repo.

+
+ +

You can now open this file in a web browser to see what the rendered code looks like, and then edit the code and refresh the browser to see what the result is. Initially it will look like this:

+ +

A simple HTML page that says This is my pageSo in this exercise, you can edit the code locally on your computer, as outlined above, or you can edit it in the editable sample window below (the editable sample window represents just the contents of the {{htmlelement("body")}} element, in this case.) We'd like you to have a go at implementing the following steps:

+ + + +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

+ + + +

{{ EmbedLiveSample('Playable_code3', 700, 600) }}

+ +

Espaço em branco em HTML

+ +

In the above examples you may have noticed that a lot of whitespace is included in the code listings — this is not necessary at all; the two following code snippets are equivalent:

+ +
<p>Dogs are silly.</p>
+
+<p>Dogs        are
+         silly.</p>
+ +

No matter how much whitespace you use (which can include space characters, but also line breaks), the HTML parser reduces each one down to a single space when rendering the code. So why use so much whitespace? The answer is readability — it is so much easier to understand what is going on in your code if you have it nicely formatted, and not just bunched up together in a big mess. In our HTML we've got each nested element indented by two spaces more than the one it is sitting inside. It is up to you what style of formatting you use (how many spaces for each level of indentation, for example), but you should consider using some kind of formatting.

+ +

Referências de entidade: incluindo carateres especiais em HTML

+ +

In HTML, the characters <, >,",' and & are special characters. They are parts of the HTML syntax itself, so how do you include one of these characters in your text, for example if you really want to use an ampersand or less than sign, and not have it interpreted as code as some browsers may do?

+ +

We have to use character references — special codes that represent characters, and can be used in these exact circumstances. Each character reference is started with an ampersand (&), and ended by a semi-colon (;).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Caráter literalReferência de caráter equivalente
<&lt;
>&gt;
"&quot;
'&apos;
&&amp;
+ +

In the below example, you can see two paragraphs, which are talking about web technologies:

+ +
<p>In HTML, you define a paragraph using the <p> element.</p>
+
+<p>In HTML, you define a paragraph using the &lt;p&gt; element.</p>
+ +

In the live output below, you can see that the first paragraph has gone wrong, because the browser thinks that the second instance of <p> is starting a new paragraph. The second paragraph looks fine, because we have replaced the angle brackets with character references.

+ +

{{ EmbedLiveSample('Entity_references_including_special_characters_in_HTML', 700, 200) }}

+ +
+

Nota: A chart of all the available HTML character entity references can be found on Wikipedia: List of XML and HTML character entity references.

+
+ +

Comentários de HTML

+ +

In HTML, as with most programming languages, there is a mechanism available to write comments in the code — comments are ignored by the browser and invisible to the user, and their purpose is to allow you to include comments in the code to say how your code works, what the different parts of the code do, etc. This can be very useful if you return to a code base that you've not worked on for six months, and can't remember what you did — or if you hand your code over to someone else to work on.

+ +

To turn a section of content inside your HTML file into a comment, you need to wrap it in the special markers <!-- and -->, for example:

+ +
<p>I'm not inside a comment</p>
+
+<!-- <p>I am!</p> -->
+ +

As you can see below, the first paragraph appears in the live output, but the second one doesn't.

+ +

{{ EmbedLiveSample('HTML_comments', 700, 100) }}

+ +

Resumo

+ +

You've reached the end of the article — we hope you enjoyed your tour of the very basics of HTML! At this point you should understand what the language looks like, how it works at a basic level, and be able to write a few elements and attributes. This is a perfect place to be right now, as in subsequent articles in the module we will go into some of the things you have already looked at in a lot more detail, and introduce some new features of the language. Stay tuned!

+ +
+

Note: At this point, as you start to learn more about HTML, you might also want to start to explore the basics of Cascading Style Sheets, or CSS. CSS is the language you use to style your web pages (whether e.g. changing the font or colors, or altering the page layout). HTML and CSS go very well together, as you'll soon discover.

+
+ +

Consulte também

+ + + +
{{NextMenu("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML")}}
+ +
+ + + + + +
diff --git a/files/pt-pt/learn/html/introduction_to_html/index.html b/files/pt-pt/learn/html/introduction_to_html/index.html new file mode 100644 index 0000000000..6e2ac788fd --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/index.html @@ -0,0 +1,64 @@ +--- +title: Introdução ao HTML +slug: Learn/HTML/Introducao_ao_HTML +tags: + - CodingScripting + - Estrutura + - HTML + - Hiperligações + - Introdução ao HTML + - Texto + - head + - semántica +translation_of: Learn/HTML/Introduction_to_HTML +--- +
{{LearnSidebar}}
+ +

Na sua essência, {{glossary("HTML")}} é uma linguagem bastante simples, composta por elementos que podem ser aplicados em partes de texto para lhes dar um significado diferente num documento (É um parágrafo? Uma lista com marcas? É parte de uma tabela?), estruturar um documento em secções lógicas (Tem um cabeçalho? Três colunas de conteúdo? Um menu de navegação?) e incorporar conteúdo como imagens e vídeos numa página. Este módulo irá apresentar as duas primeiras aplicações e introduzir os conceitos e a sintaxe fundamentais que você precisa de saber para compreender HTML.

+ +

Pré-requisitos

+ +

Antes de começar este módulo, não precisa de ter qualquer conhecimento prévio de  HTML, mas deve pelo menos ter alguma familiaridade com utilização de computadores, e utilização passiva da Web (ou seja, apenas na perspectiva de consumidor e não de criação e publicação de conteúdos). Deverá ter um ambiente de trabalho básico configurado de acordo com as indicações que pode encontrar em Instalar software básico, e compreender como se criam e gerem ficheiros, como indicado na secção Lidar com ficheiros — estas duas secções fazem ambas parte do nosso módulo completo de iniciação em Primeiros passos na web.

+ +
+

Nota: Se está a trabalhar num computador, tablet ou outro dispositivo em que não tem possibilidade de criar ficheiros, pode testar a maioria dos exemplos de código num programa de edição de código online como o JSBin ou o Thimble.

+
+ +

Guias

+ +

Este módulo contém os seguintes artigos, os quais vão guiá-lo ao longo da teoria básica de HTML, e dar-lhe amplas oportunidades para experimentar o que aprendeu.

+ +
+
Começar com HTML
+
Para começar, cobrimos as bases absolutas do HTML — definir elementos, atributos e todos os termos importantes de que já ouviu falar, e como se encaixam na linguagem. Também mostramos a estrutura de um elemento HTML, a estrutura de uma página HTML típica e explicamos outras funcionalidades básicas mas importantes da linguagem. Ao longo do caminho, vamos brincar com algum HTML, para lhe despertar o interesse!
+
O que lhe vai no cabeçalho? Metadadados em HTML
+
O cabeçalho de um documento HTML é parte que não é mostrada no navegador quando a página é carregada. Contém informação como o título da página ({{htmlelement("title")}}), ligações para {{glossary("CSS")}} (se quiser estilizar o conteúdo HTML com CSS), ligações a ícones personalizados, e metadados (dados sobre HTML, por exemplo, quem o escreveu e palavras-chave importantes que descrevem o documento).
+
Fundamentos do texto HTML
+
Uma das principais funções do HTML é atribuir significado (semântica) ao texto, para que o navegador o apresente corretamente. Este artigo explora como utilizar HTML para repartir o bloco de texto em títulos e parágrafos, dar ênfase/importância a palavras, criar listas e mais.
+
Criar hiperligações
+
Hiperligações são muito importantes — são o que torna a internet na internet. Este artigo mostra a sintaxe necessária para criar uma ligação (um link), e discute boas práticas a ter quando se criam hiperligações.
+
Formatação avançada de texto
+
Há muitos outros elementos em HTML para formatar texto, que não vimos em Fundamentos do texto HTML. Estes elementos são menos conhecidos, mas é útil conhecê-los. Neste artigo aprenderá a demarcar citações, listas de descrições, código de computador e outro texto relacionado, texto sobre e por baixo da linha, informação de contactos e mais.
+
Estrutura do documento e do website
+
Além de definir partes individuais da página (como parágrafos e imagens), HTML também define secções do site (como cabeçalho, menu de navegação, coluna principal de conteúdo). Este artigo aborda como planear a estrutura básica de um site e como escrever HTML que represente essa estrutura.
+
Depurar HTML
+
É ótimo escrever HTML, mas como proceder se alguma coisa correr mal e não conseguir descobrir em que parte do código está o erro? Este artigo introduz algumas ferramentas que pode utilizar.
+
+ +

Avaliações

+ +

Estas avaliações testam o seu conhecimento das bases de HTML abrangidas nos guias suprarreferidos.

+ +
+
Demarcar uma carta
+
Todos aprendemos a escrever uma carta mais cedo ou mais tarde; e é um exemplo útil para testar as nossas capacidades de formatação de texto! Nesta avaliação, damos-lhe uma carta para demarcar.
+
Estruturar uma página de conteúdo
+
Esta avaliação testa a sua capacidade de recorrer a HTML para estruturar uma página de conteúdo simples, que contém cabeçalho, rodapé, menu de navegação, conteúdo principal e barra lateral.
+
+ +

Consultar também

+ +
+
Básicos de literacia da Web 1 (inglês)
+
Um curso excelente da fundação Mozilla que explora e testa muitas das habilidades faladas no módulo de Introdução ao HTML. Os principiantes familiarizam-se com a leitura, escrita e participação na Web neste módulo de seis partes. Descubra as fundações da Web através da produção e colaboração.
+
diff --git a/files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html b/files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html new file mode 100644 index 0000000000..0545b789e0 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html @@ -0,0 +1,104 @@ +--- +title: Demarcar uma carta +slug: Learn/HTML/Introducao_ao_HTML/demarcar_uma_carta +tags: + - Avaliação + - HTML + - Ligações + - Principiante + - Texto +translation_of: Learn/HTML/Introduction_to_HTML/Marking_up_a_letter +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content", "Learn/HTML/Introduction_to_HTML")}}
+ +

We all learn to write a letter sooner or later; it is also a useful example to test out our text formatting skills! In this assessment you'll be given a letter to mark up to test basic and advanced HTML text formatting skills, including hyperlinks, plus we'll test your familiarity with some HTML <head> contents.

+ + + + + + + + + + + + +
Prerequisites:Before attempting this assessment you should have already worked through Getting started with HTML, What's in the head? Metadata in HTML, HTML text fundamentals, Creating hyperlinks, and Advanced text formatting.
Objective:To test basic and advanced HTML text formatting and hyperlink skills, and knowledge of what goes in the HTML <head>.
+ +

Starting point

+ +

To get this assessment started, you should go and grab the raw text you need to mark up, and the CSS you need to include in your HTML. Create a new .html file using your text editor to do your work in (or alternatively use a site like JSBin or Thimble to do your assessment.)

+ +

Project brief

+ +

For this project, your task is to mark up a letter that needs to be hosted on a university intranet. The letter is a response from a research fellow to a prospective PhD student concerning their application to the university.

+ +

Block/structural semantics:

+ + + +

Inline semantics:

+ + + +

The head of the document:

+ + + +

Hints and tips

+ + + +

Example

+ +

The following screenshot shows an example of what the letter might look like after being marked up.

+ +

Example

+ +

Assessment

+ +

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread about this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content", "Learn/HTML/Introduction_to_HTML")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html b/files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html new file mode 100644 index 0000000000..1f6310a395 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html @@ -0,0 +1,107 @@ +--- +title: Estruturar uma página de conteúdo +slug: Learn/HTML/Introducao_ao_HTML/Estruturar_pagina_de_conteudo +tags: + - Avaliação + - Estrutura + - HTML + - Principiante + - semántica +translation_of: Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
+ +

Structuring a page of content ready for laying it out using CSS is a very important skill to master, so in this assessment you'll be tested on your ability to think about how a page might end up looking, and choose appropriate structural semantics to build a layout on top of.

+ + + + + + + + + + + + +
Prerequisites:Before attempting this assessment you should have already worked through the rest of the course, with a particular emphasis on Document and website structure.
Objective:To test knowledge of web page structures, and how to represent a prospective layout design in markup.
+ +

Starting point

+ +

To get this assessment started, you should go and grab the zip file containing all the starting assets. The zip file contains:

+ + + +

Create the example on your local computer, or alternatively use a site like JSBin or Thimble to do your assessment.

+ +

Project brief

+ +

For this project, your task is to take the content for the homepage of a bird watching website and add structural elements to it so it can have a page layout applied to it. It needs to have:

+ + + +

You need to add a suitable wrapper for:

+ + + +

You should also:

+ + + +

Hints and tips

+ + + +

Example

+ +

The following screenshot shows an example of what the homepage might look like after being marked up.

+ +

The finished example for the assessment; a simple webpage about birdwatching, including a heading of "Birdwatching", bird photos, and a welcome message

+ +

Assessment

+ +

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread about this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

+ +

{{PreviousMenu("Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html b/files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html new file mode 100644 index 0000000000..099166b821 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html @@ -0,0 +1,346 @@ +--- +title: O que está em "head"? Metadados em HTML +slug: Learn/HTML/Introducao_ao_HTML/Os_metadados_de_head_em_HTML +tags: + - Guía + - HTML + - Idioma + - Meta + - Principiante + - head + - metadados +translation_of: Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introducao_ao_HTML")}}
+ +

{{glossary("Head", "Head")}} de um documento HTML é a parte que não é exibida no navegador da Web quando a página é carregada. Este contém a informação, tais como o {{htmlelement("title", "título")}} da página, hiperligações para {{glossary("CSS")}} (se pretender estilizar o seu conteúdo HTML com CSS), hiperligações para favicons personalizados, e outros metadados (dados sobre o HTML, tais como quem o escreveu, e palavras-chave importantes que descrevem o documento.) Neste artigo nós iremos abranger todas as coisas acima e muito mais, para lhe dar bons conceitos básicos para lidar com a marcação e outro código que deverá estar no seu head.

+ + + + + + + + + + + + +
Pré-requisitos:Basic HTML familiarity, as covered in Getting started with HTML.
Objetivo:To learn about the HTML head, what its purpose is, the most important items it can contain, and what effect it can have on the HTML document.
+ +

O que é head no HTML?

+ +

Let's revisit the simple HTML document we covered in the previous article:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My test page</title>
+  </head>
+  <body>
+    <p>This is my page</p>
+  </body>
+</html>
+ +

The HTML head is the contents of the {{htmlelement("head")}} element — unlike the contents of the {{htmlelement("body")}} element (which are displayed on the page when loaded in a browser), the head's content is not displayed on the page. Instead, the head's job is to contain {{glossary("Metadata", "metadata")}} about the document. In the above example, the head is quite small:

+ +
<head>
+  <meta charset="utf-8">
+  <title>My test page</title>
+</head>
+ +

In larger pages however, the head can get quite full of items — try going to some of your favorite websites and using the developer tools to check out their head contents. Our aim here is not to show you how to use everything that can possibly be put in the head, but rather to teach you how to use the most obvious things you'll want to include in the head, and give you some familiarity. Let's get started.

+ +

Adding a title

+ +

We've already seen the {{htmlelement("title")}} element in action — this can be used to add a title to the document. This however can get confused with the {{htmlelement("h1")}} element, which is used to add a top level heading to your body content — this is also sometimes referred to as the page title. But they are different things!

+ + + +

Active learning: Inspecting a simple example

+ +
    +
  1. To start off this active learning, we'd like you to go to our GitHub repo and download a copy of our title-example.html page. To do this, either + +
      +
    1. Copy and paste the code out of the page and into a new text file in your code editor, then save it in a sensible place.
    2. +
    3. Press the "Raw" button on the page, which causes the raw code to appear in a new browser tab. Next, from your browser's menu choose File > Save Page As... in your browser's menu then choose a place to save the file.
    4. +
    +
  2. +
  3. Now open the file in your browser. You should see something like this: +

    A simple web page with the title set to <title> element, and the <h1> set to <h1> element.It should now be completely obvious where the <h1> content appears, and where the <title> content appears!

    +
  4. +
  5. You should also try opening the code up in your code editor, editing the contents of these elements, then refreshing the page in your browser. Have some fun with it.
  6. +
+ +

The <title> element contents are also used in other ways. For example, if you try bookmarking the page (Bookmarks > Bookmark This Page or the star icon in the URL bar in Firefox), you will see the <title> contents filled in as the suggested bookmark name.

+ +

A webpage being bookmarked in firefox; the bookmark name has been automatically filled in with the contents of the <title> element

+ +

The <title> contents are also used in search results, as you'll see below.

+ +

Metadata: the <meta> element

+ +

Metadata is data that describes data, and HTML has an "official" way of adding metadata to a document — the {{htmlelement("meta")}} element. Of course, the other stuff we are talking about in this article could also be thought of as metadata too. There are a lot of different types of <meta> element that can be included in your page's <head>, but we won't try to explain them all at this stage, as it would just get too confusing. Instead, we'll explain a few things that you might commonly see, just to give you an idea.

+ +

Specifying your document's character encoding

+ +

In the example we saw above, this line was included:

+ +
<meta charset="utf-8">
+ +

This element simply specifies the document's character encoding — the character set that the document is permitted to use. utf-8 is a universal character set that includes pretty much any character from any human language. This means that your web page will be able to handle displaying any language; it's therefore a good idea to set this on every web page you create! For example, your page could handle English and Japanese just fine:

+ +

a web page containing English and Japanese characters, with the character encoding set to universal, or utf-8. Both languages display fine,If you set your character encoding to ISO-8859-1, for example (the character set for the Latin alphabet), your page rendering would be all messed up:

+ +

a web page containing English and Japanese characters, with the character encoding set to latin. The Japanese characters don't display correctly

+ +

Active learning: Experiment with character encoding

+ +

To try this out, revisit the simple HTML template you obtained in the previous section on <title> (the title-example.html page), try changing the meta charset value to ISO-8859-1, and add the Japanese to your page. This is the code we used:

+ +
<p>Japanese example: ご飯が熱い。</p>
+ +

Adding an author and description

+ +

Many <meta> elements include name and content attributes:

+ + + +

Two such meta elements that are useful to include on your page define the author of the page, and provide a concise description of the page. Let's look at an example:

+ +
<meta name="author" content="Chris Mills">
+<meta name="description" content="The MDN Learning Area aims to provide
+complete beginners to the Web with all they need to know to get
+started with developing web sites and applications.">
+ +

Specifying an author is useful in a few ways: it is useful to be able to work out who wrote the page, if you want to contact them with questions about the content. Some content management systems have facilities to automatically extract page author information and make it available for such purposes.

+ +

Specifying a description that includes keywords relating to the content of your page is useful as it has the potential to make your page appear higher in relevant searches performed in search engines (such activities are termed Search Engine Optimization, or {{glossary("SEO")}}.)

+ +

Active learning: The description's use in search engines

+ +

The description is also used on search engine result pages. Let's go through an exercise to explore this

+ +
    +
  1. Go to the front page of The Mozilla Developer Network.
  2. +
  3. View the page's source (Right/Ctrl + click on the page, choose View Page Source from the context menu.)
  4. +
  5. Find the description meta tag. It will look like this: +
    <meta name="description" content="The Mozilla Developer Network (MDN) provides
    +information about Open Web technologies including HTML, CSS, and APIs for both
    +Web sites and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
    +
  6. +
  7. Now search for "Mozilla Developer Network" in your favorite search engine (We used Yahoo.) You'll notice the description <meta> and <title> element content used in the search result — definitely worth having! +

    A Yahoo search result for "Mozilla Developer Network"

    +
  8. +
+ +
+

Note: In Google, you will see some relevant subpages of MDN listed below the main MDN homepage link — these are called sitelinks, and are configurable in Google's webmaster tools — a way to make your site's search results better in the Google search engine.

+
+ +
+

Note: Many <meta> features just aren't used any more. For example, the keyword <meta> element (<meta name="keywords" content="fill, in, your, keywords, here">) — which is supposed to provide keywords for search engines to determine relevance of that page for different search terms — is ignored by search engines, because spammers were just filling the keyword list with hundreds of keywords, biasing results.

+
+ +

Other types of metadata

+ +

As you travel around the web, you'll find other types of metadata, too. A lot of the features you'll see on websites are proprietary creations, designed to provide certain sites (such as social networking sites) with specific pieces of information they can use.

+ +

For example, Open Graph Data is a metadata protocol that Facebook invented to provide richer metadata for websites. In the MDN sourcecode, you'll find this:

+ +
<meta property="og:image" content="https://developer.cdn.mozilla.net/static/img/opengraph-logo.dc4e08e2f6af.png">
+<meta property="og:description" content="The Mozilla Developer Network (MDN) provides
+information about Open Web technologies including HTML, CSS, and APIs for both Web sites
+and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
+<meta property="og:title" content="Mozilla Developer Network">
+ +

One effect of this is that when you link to MDN on facebook, the link appears along with an image and description: a richer experience for users.

+ +

Open graph protocol data from the MDN homepage as displayed on facebook, showing an image, title, and description.Twitter also has its own similar proprietary metadata, which has a similar effect when the site's URL is displayed on twitter.com. For example:

+ +
<meta name="twitter:title" content="Mozilla Developer Network">
+ +

Adding custom icons to your site

+ +

To further enrich your site design, you can add references to custom icons in your metadata, and these will be displayed in certain contexts.

+ +

The humble favicon, which has been around for many years, was the first icon of this type, a 16 x 16 pixel icon used in multiple places. You'll see favicons displayed in the browser tab containing each open page, and next to bookmarked pages in the bookmarks panel.

+ +

A favicon can be added to your page by:

+ +
    +
  1. Saving it in the same directory as the site's index page, saved in .ico format (most browsers will support favicons in more common formats like .gif or .png, but using the ICO format will ensure it works as far back as Internet Explorer 6.)
  2. +
  3. Adding the following line into your HTML <head> to reference it: +
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    +
  4. +
+ +

Here is an example of a favicon in a bookmarks panel:

+ +

The Firefox bookmarks panel, showing a bookmarked example with a favicon displayed next to it.

+ +

There are lots of other icon types to consider these days as well. For example, you'll find this in the source code of the MDN homepage:

+ +
<!-- third-generation iPad with high-resolution Retina display: -->
+<link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://developer.cdn.mozilla.net/static/img/favicon144.a6e4162070f4.png">
+<!-- iPhone with high-resolution Retina display: -->
+<link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://developer.cdn.mozilla.net/static/img/favicon114.0e9fabd44f85.png">
+<!-- first- and second-generation iPad: -->
+<link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://developer.cdn.mozilla.net/static/img/favicon72.8ff9d87c82a0.png">
+<!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
+<link rel="apple-touch-icon-precomposed" href="https://developer.cdn.mozilla.net/static/img/favicon57.a2490b9a2d76.png">
+<!-- basic favicon -->
+<link rel="shortcut icon" href="https://developer.cdn.mozilla.net/static/img/favicon32.e02854fdcf73.png">
+ +

The comments explain what each icon is used for — these elements cover things like providing a nice high resolution icon to use when the website is saved to an iPad's home screen.

+ +

Don't worry too much about implementing all these types of icon right now — this is a fairly advanced feature, and you won't be expected to have knowledge of this to progress through the course. The main purpose here is to let you know what such things are, in case you come across them while browsing other websites' source code.

+ +

Applying CSS and JavaScript to HTML

+ +

Just about all websites you'll use in the modern day will employ {{glossary("CSS")}} to make them look cool, and {{glossary("JavaScript")}} to power interactive functionality, such as video players, maps, games, and more. These are most commonly applied to a web page using the {{htmlelement("link")}} element and the {{htmlelement("script")}} element, respectively.

+ + + +

Active learning: applying CSS and JavaScript to a page

+ +
    +
  1. To start this active learning, grab a copy of our meta-example.html, script.js and style.css files, and save them on your local computer in the same directory. Make sure they are saved with the correct names and file extensions.
  2. +
  3. Open the HTML file in both your browser, and your text editor.
  4. +
  5. By following the information given above, add {{htmlelement("link")}} and {{htmlelement("script")}} elements to your HTML, so that your CSS and JavaScript are applied to your HTML.
  6. +
+ +

If done correctly, when you save your HTML and refresh your browser you'll see that things have changed:

+ +

Example showing a page with CSS and JavaScript applied to it. The CSS has made the page go green, whereas the JavaScript has added a dynamic list to the page.

+ + + +
+

Note: If you get stuck in this exercise and can't get the CSS/JS to apply, try checking out our css-and-js.html example page.

+
+ +

Setting the primary language of the document

+ +

Finally, it's worth mentioning that you can (and really should) set the language of your page. This can be done by adding the lang attribute to the opening HTML tag (as seen in the meta-example.html and shown below.)

+ +
<html lang="en-US">
+ +

This is useful in many ways. Your HTML document will be indexed more effectively by search engines if its language is set (allowing it to appear correctly in language-specific results, for example), and it is useful to people with visual impairments using screen readers (for example, the word "six" exists in both French and English, but is pronounced differently.)

+ +

You can also set subsections of your document to be recognised as different languages. For example, we could set our Japanese language section to be recognised as Japanese, like so:

+ +
<p>Japanese example: <span lang="jp">ご飯が熱い。</span>.</p>
+ +

These codes are defined by the ISO 639-1 standard. You can find more about them in Language tags in HTML and XML.

+ +

Resumo

+ +

That marks the end of our quickfire tour of the HTML head — there's a lot more you can do in here, but an exhaustive tour would be boring and confusing at this stage, and we just wanted to give you an idea of the most common things you'll find in there for now! In the next article we'll be looking at HTML text fundamentals.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML")}}

+ +
+ + + + + +
diff --git a/files/pt-pt/learn/html/multimedia_and_embedding/index.html b/files/pt-pt/learn/html/multimedia_and_embedding/index.html new file mode 100644 index 0000000000..724e0ca3f5 --- /dev/null +++ b/files/pt-pt/learn/html/multimedia_and_embedding/index.html @@ -0,0 +1,69 @@ +--- +title: Multimédia e integração +slug: Learn/HTML/Multimedia_e_integracao +tags: + - Aprender + - Audio + - Avaliação + - CodingScripting + - Flash + - Guía + - HTML + - Imagens + - Landing + - Principiante + - Responsivo + - SVG + - Video + - iframes + - mapas de imagem +translation_of: Learn/HTML/Multimedia_and_embedding +--- +

{{LearnSidebar}}

+ +

Nós já vimos muito texto até agora neste curso, mas a Web seria realmente chata se se utilizasse apenas texto. Vamos começar a ver como dar vida à Web, com conteúdo mais interessante! Este módulo explora como utilizar HTML para incluir multimédia nas suas páginas da Web, incluindo os modos diferentes em que as imagens podem ser incluídas, e como incorporar vídeo, áudio e até páginas da Web completas.

+ +

Pré-requisitos

+ +

Antes de iniciar este módulo, deverá ter um conhecimento razoável dos conceitos básicos de HTML, como anteriormente abordado em Introdução ao HTML. Se ainda não leu este módulo (ou qualquer coisa similar), leia-o primeiro, e depois volte aqui!

+ +
+

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

+
+ +

Guias

+ +

This module contains the following articles, which will take you through all the fundamentals of embedding multimedia on webpages.

+ +
+
Imagens em HTML
+
There are other types of multimedia to consider, but it is logical to start with the humble {{htmlelement("img")}} element, used to embed a simple image in a webpage. In this article we'll look at how to use it in more depth, including basics, annotating it with captions using {{htmlelement("figure")}}, and how it relates to CSS background images.
+
Conteúdo de vídeo e de áudio
+
Next, we'll look at how to use the HTML5 {{htmlelement("video")}} and {{htmlelement("audio")}} elements, to embed video and audio on our pages; including basics, providing access to different file formats to different browsers, adding captions and subtitles, and how to add fallbacks for older browsers.
+
De <object> para <iframe> — outras tecnologias de integração
+
At this point we'd like to take somewhat of a sideways step, looking at a couple of elements that allow you to embed a wide variety of content types into your webpages: the {{htmlelement("iframe")}}, {{htmlelement("embed")}} and {{htmlelement("object")}} elements. <iframe>s are for embedding other web pages, and the other two allow you to embed PDFs, SVG, and even Flash — a technology on its way out, but which you may still see semi-regularly.
+
Adicionar gráficos de vetor à Web
+
Vector graphics can be very useful in certain situations. Unlike regular formats like PNG/JPG, they don't distort/pixelate when zoomed in — they can remain smooth when scaled. This article introduces you to what vector graphics are, and how to include the popular {{glossary("SVG")}} format in web pages.
+
Imagens responsivas
+
With so many different device types now able to browse the Web — from mobile phones to desktop computers — an essential concept to master in the modern web world is responsive design. This refers to the creation of webpages that can automatically change their features to suit different screen sizes, resolutions, etc. This will be looked at in much more detail in a CSS module later on, but for now we'll look at the tools HTML has available to create responsive images, including the {{htmlelement("picture")}} element.
+
+ +

Avaliações

+ +

The following assessments will test your understanding of the HTML basics covered in the guides above:

+ +
+
Página de boas-vindas da Mozilla
+
In this assessment, we'll test your knowledge of some of the techniques discussed in this module's articles, getting you to add some images and video to a funky splash page all about Mozilla!
+
+ +

Consulte também

+ +
+
Adicionar um mapa clicável no topo de uma imagem
+
Image maps provide a mechanism to make different parts of an image link to different places (think of a map, linking through to further information about each different country you click on.) This technique can sometimes be useful.
+
Literacia da Web - básicos 2
+
+

An excellent Mozilla foundation course that explores and tests some of the skills talked about in the Multimedia and embedding module. Dive deeper into the basics of composing webpages, designing for accessibility, sharing resources, using online media, and working open (meaning that your content is freely available, and shareable by others).

+
+
diff --git a/files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html b/files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html new file mode 100644 index 0000000000..aad765e97a --- /dev/null +++ b/files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html @@ -0,0 +1,194 @@ +--- +title: 'Avaliação: Página inicial da Mozilla' +slug: Learn/HTML/Multimedia_and_embedding/Pagina_de_boas_vindas_da_Mozilla +tags: + - Avaliação + - HTML + - Imagens + - Incorporação + - Multimedia + - Principiante + - Responsivo + - Video + - iframe + - imagem + - tamanhos +translation_of: Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}
+ +

Nesta parte, testaremos seu conhecimento de algumas técnicas discutidas nos artigos deste módulo, pedindo que você adicione imagens e vídeos a uma grande página inteiramente dedicada ao Mozilla!

+ + + + + + + + + + + + +
Pré-requisitos:Antes de abordar este estudo, você já deve ter trabalhado nos parágrafos anteriores do módulo Multimídia e Integração.
Objetivo:Testar seus conhecimentos sobre a integração de imagens e vídeos em páginas da Web, bem como técnicas de imagens adaptativas (imagens "responsivas").
+ +

Ponto de partida

+ +

Para iniciar este estudo, você precisa buscar todas as imagens e HTML disponíveis no diretório mdn-splash-page-start no github. Coloque o conteúdo do arquivo index.htmlem um arquivo chamado index.htmlem seu disco rígido local, em um novo diretório. Em seguida, copie pattern.png na mesma pasta (clique com o botão direito sobre a imagem para obter a opção de salvá-la).

+ +

Vá para o diretório original para  procurar por imagens diferentes e fazer a mesma coisa. Talvez seja necessário salvá-las em uma nova pasta por enquanto, caso você precise manipular algumas delas usando um editor gráfico antes de usá-las.

+ +
+

Note: O arquivo HTML de exemplo contém bastante CSS para estilizar a página. Você não precisa alterar o CSS, apenas o HTML no elemento <body> - contanto que você insira as tags corretas, o estilo corresponderá à essas alterações.

+
+ +

Sumário do projeto

+ +

Nesta parte, apresentamos uma home page quase acabada da Mozilla, que visa dizer algo interessante sobre o que a Mozilla representa e fornecer alguns links para outros recursos. Infelizmente, nenhuma imagem ou vídeo foi adicionado ainda - este é o seu trabalho! Você precisa adicionar algumas mídias para tornar a página mais bonita e fazer mais sentido. As subseções a seguir detalham o que você precisa fazer:

+ +

Preparando as imagens

+ +

Usando seu editor de imagem favorito, crie versões com 400px de largura por 120px de largura de:

+ + + +

Dê a eles nomes semelhantes como:  firefoxlogo400.png e firefoxlogo120.png.

+ +

Juntamente com o mdn.svg, essas imagens serão seus ícones para vincular a outros recursos, dentro da área further-info. Você também vinculará o logotipo do Firefox no cabeçalho do site. Salve cópias de todos estes arquivos dentro do mesmo diretório de index.html.

+ +

Em seguida, crie uma versão com 1200px de largura, no modo paisagem, de red-panda.jpg, e outra, com 600px de largura, no modo retrato, que mostre o panda em close-up. Mais uma vez, nomeie-os de forma semelhante para identificá-los facilmente. Salve todas essas cópias na mesma pasta que o index.html.

+ +
+

Nota: Você deve otimizar suas imagens em JPG e PNG para torná-las o menor possível e, ao mesmo tempo, de boa qualidade. O tinypng.com é uma boa ajuda para fazer isso facilmente.

+
+ +

Adicionando um logotipo ao cabeçalho

+ +

Dentro do elemento <header>, adicione um elemento <img> que incluirá uma versão pequena do logotipo do Firefox no cabeçalho.

+ +

Adicionando um vídeo ao conteúdo do artigo principal

+ +

No item <article>  (logo abaixo da tag de abertura), incorpore o vídeo do YouTube encontrado aqui: https://www.youtube.com/watch?v=ojcNcvb1olg, usando as ferramentas apropriadas do YouTube para gerar o código. O vídeo terá que ter 400px de largura.

+ + + +

No elemento <div>, na classe further-info você encontrará quatro outros elementos <a> - cada um deles vinculado a uma página interessante relacionada ao Mozilla. Para concluir esta seção, você irá inserir um elemento <img> contendo os atributos srcaltsrcset e sizes de forma apropriada.

+ +

 

+ +

Queremos que cada imagem (exceto quando a mesma for responsiva) use uma imagem de 120px quando a largura da janela de visualização do navegador for menor ou igual a 480px e, em outros casos, escolha uma versão de 400px.

+ +

Verifique se o link correto corresponde à imagem correta!

+ +

 

+ +
+

Nota: Para testar adequadamente os exemplos srcset/sizes, você deve fazer o upload do seu site em um servidor (use as páginas Github, é uma solução simples e livre), e então você poderá testar, se tudo correr corretamente, usando as ferramentas de desenvolvimento, como explicado em Imagens Responsivas: ferramentas úteis para desenvolvedores.

+
+ +

Um panda vermelho criativo

+ +

No elemento <div> da classe red-panda, queremos inserir um elemento <picture> que exiba o o modo retrato do panda se o quadro tiver 600px de largura, ou menos, e o modo paisagem do panda em outros casos.

+ +

Exemplo

+ +

A captura de tela a seguir mostra como a página inicial deve ficar depois de marcada corretamente, com uma tela ampla e outra estreita.

+ +

A wide shot of our example splash page

+ +

A narrow shot of our example splash page

+ +

Avaliação

+ +

Se você está seguindo este estudo como parte de um programa de curso organizado, você deve poder mostrar seu trabalho ao seu professor/mentor para correção. Se você aprender sozinho, você pode obter informações e correções perguntando no tópico sobre este exercício, ou no canal de IRC #mdn no IRC da MozillaTente fazer o exercício primeiro - você não ganha nada enganando!

+ +

{{PreviousMenu("Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}

+ +
+ + + + + +
diff --git a/files/pt-pt/learn/html/multimedia_and_embedding/pagina_de_boas_vindas_da_mozilla/index.html b/files/pt-pt/learn/html/multimedia_and_embedding/pagina_de_boas_vindas_da_mozilla/index.html deleted file mode 100644 index aad765e97a..0000000000 --- a/files/pt-pt/learn/html/multimedia_and_embedding/pagina_de_boas_vindas_da_mozilla/index.html +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: 'Avaliação: Página inicial da Mozilla' -slug: Learn/HTML/Multimedia_and_embedding/Pagina_de_boas_vindas_da_Mozilla -tags: - - Avaliação - - HTML - - Imagens - - Incorporação - - Multimedia - - Principiante - - Responsivo - - Video - - iframe - - imagem - - tamanhos -translation_of: Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}
- -

Nesta parte, testaremos seu conhecimento de algumas técnicas discutidas nos artigos deste módulo, pedindo que você adicione imagens e vídeos a uma grande página inteiramente dedicada ao Mozilla!

- - - - - - - - - - - - -
Pré-requisitos:Antes de abordar este estudo, você já deve ter trabalhado nos parágrafos anteriores do módulo Multimídia e Integração.
Objetivo:Testar seus conhecimentos sobre a integração de imagens e vídeos em páginas da Web, bem como técnicas de imagens adaptativas (imagens "responsivas").
- -

Ponto de partida

- -

Para iniciar este estudo, você precisa buscar todas as imagens e HTML disponíveis no diretório mdn-splash-page-start no github. Coloque o conteúdo do arquivo index.htmlem um arquivo chamado index.htmlem seu disco rígido local, em um novo diretório. Em seguida, copie pattern.png na mesma pasta (clique com o botão direito sobre a imagem para obter a opção de salvá-la).

- -

Vá para o diretório original para  procurar por imagens diferentes e fazer a mesma coisa. Talvez seja necessário salvá-las em uma nova pasta por enquanto, caso você precise manipular algumas delas usando um editor gráfico antes de usá-las.

- -
-

Note: O arquivo HTML de exemplo contém bastante CSS para estilizar a página. Você não precisa alterar o CSS, apenas o HTML no elemento <body> - contanto que você insira as tags corretas, o estilo corresponderá à essas alterações.

-
- -

Sumário do projeto

- -

Nesta parte, apresentamos uma home page quase acabada da Mozilla, que visa dizer algo interessante sobre o que a Mozilla representa e fornecer alguns links para outros recursos. Infelizmente, nenhuma imagem ou vídeo foi adicionado ainda - este é o seu trabalho! Você precisa adicionar algumas mídias para tornar a página mais bonita e fazer mais sentido. As subseções a seguir detalham o que você precisa fazer:

- -

Preparando as imagens

- -

Usando seu editor de imagem favorito, crie versões com 400px de largura por 120px de largura de:

- - - -

Dê a eles nomes semelhantes como:  firefoxlogo400.png e firefoxlogo120.png.

- -

Juntamente com o mdn.svg, essas imagens serão seus ícones para vincular a outros recursos, dentro da área further-info. Você também vinculará o logotipo do Firefox no cabeçalho do site. Salve cópias de todos estes arquivos dentro do mesmo diretório de index.html.

- -

Em seguida, crie uma versão com 1200px de largura, no modo paisagem, de red-panda.jpg, e outra, com 600px de largura, no modo retrato, que mostre o panda em close-up. Mais uma vez, nomeie-os de forma semelhante para identificá-los facilmente. Salve todas essas cópias na mesma pasta que o index.html.

- -
-

Nota: Você deve otimizar suas imagens em JPG e PNG para torná-las o menor possível e, ao mesmo tempo, de boa qualidade. O tinypng.com é uma boa ajuda para fazer isso facilmente.

-
- -

Adicionando um logotipo ao cabeçalho

- -

Dentro do elemento <header>, adicione um elemento <img> que incluirá uma versão pequena do logotipo do Firefox no cabeçalho.

- -

Adicionando um vídeo ao conteúdo do artigo principal

- -

No item <article>  (logo abaixo da tag de abertura), incorpore o vídeo do YouTube encontrado aqui: https://www.youtube.com/watch?v=ojcNcvb1olg, usando as ferramentas apropriadas do YouTube para gerar o código. O vídeo terá que ter 400px de largura.

- - - -

No elemento <div>, na classe further-info você encontrará quatro outros elementos <a> - cada um deles vinculado a uma página interessante relacionada ao Mozilla. Para concluir esta seção, você irá inserir um elemento <img> contendo os atributos srcaltsrcset e sizes de forma apropriada.

- -

 

- -

Queremos que cada imagem (exceto quando a mesma for responsiva) use uma imagem de 120px quando a largura da janela de visualização do navegador for menor ou igual a 480px e, em outros casos, escolha uma versão de 400px.

- -

Verifique se o link correto corresponde à imagem correta!

- -

 

- -
-

Nota: Para testar adequadamente os exemplos srcset/sizes, você deve fazer o upload do seu site em um servidor (use as páginas Github, é uma solução simples e livre), e então você poderá testar, se tudo correr corretamente, usando as ferramentas de desenvolvimento, como explicado em Imagens Responsivas: ferramentas úteis para desenvolvedores.

-
- -

Um panda vermelho criativo

- -

No elemento <div> da classe red-panda, queremos inserir um elemento <picture> que exiba o o modo retrato do panda se o quadro tiver 600px de largura, ou menos, e o modo paisagem do panda em outros casos.

- -

Exemplo

- -

A captura de tela a seguir mostra como a página inicial deve ficar depois de marcada corretamente, com uma tela ampla e outra estreita.

- -

A wide shot of our example splash page

- -

A narrow shot of our example splash page

- -

Avaliação

- -

Se você está seguindo este estudo como parte de um programa de curso organizado, você deve poder mostrar seu trabalho ao seu professor/mentor para correção. Se você aprender sozinho, você pode obter informações e correções perguntando no tópico sobre este exercício, ou no canal de IRC #mdn no IRC da MozillaTente fazer o exercício primeiro - você não ganha nada enganando!

- -

{{PreviousMenu("Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}

- -
- - - - - -
diff --git a/files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html b/files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html new file mode 100644 index 0000000000..2ab6414459 --- /dev/null +++ b/files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html @@ -0,0 +1,369 @@ +--- +title: Conteúdo de áudio e vídeo +slug: Learn/HTML/Multimedia_e_integracao/Conteudo_de_audio_e_vídeo +tags: + - Artigo + - Audio + - Guía + - HTML + - Principiante + - Video + - faixa + - legendas +translation_of: Learn/HTML/Multimedia_and_embedding/Video_and_audio_content +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}
+ +

Now that we are comfortable with adding simple images to a webpage, the next step is to start adding video and audio players to your HTML documents! In this article we'll look at doing just that with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements; we'll then finish off by looking at how to add captions/subtitles to your videos.

+ + + + + + + + + + + + +
Pré-requisitos:Basic computer literacy, basic software installed, basic knowledge of working with files, familiarity with HTML fundamentals (as covered in Getting started with HTML) and Images in HTML.
Objetivo:To learn how to embed video and audio content into a webpage, and add captions/subtitles to video.
+ +

Áudio e vídeo na Web

+ +

Web developers have wanted to use video and audio on the Web for a long time, ever since the early 2000s, when we started to have bandwidth fast enough to support any kind of video (video files are much larger than text or even images.) In the early days, native web technologies such as HTML didn't have the ability to embed video and audio on the Web, so proprietary (or plugin-based) technologies like Flash (and later, Silverlight) became popular for handling such content. This kind of technology worked ok, but it had a number of problems, including not working well with HTML/CSS features, security issues, and accessibility issues.

+ +

A native solution would solve much of this if done right. Fortunately, a few years later the {{glossary("HTML5")}} specification had such features added, with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements, and some shiny new {{Glossary("JavaScript")}} {{Glossary("API","APIs")}} for controlling them. We'll not be looking at JavaScript here — just the basic foundations that can be achieved with HTML.

+ +

We won't be teaching you how to produce audio and video files — that requires a completely different skillset. We have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own.

+ +
+

Nota: Before you begin here, you should also know that there are a quite a few {{glossary("OVP","OVPs")}} (online video providers) like YouTube, Dailymotion, and Vimeo, and online audio providers like Soundcloud. Such companies offer a convenient, easy way to host and consume videos, so you don't have to worry about the enormous bandwidth consumption. OVPs even usually offer ready-made code for embedding video/audio in your webpages. If you go that route, you can avoid some of the difficulties we discuss in this article. We'll be discussing this kind of service a bit more in the next article.

+
+ +

O elemento <video>

+ +

The {{htmlelement("video")}} element allows you to embed a video very easily. A really simple example looks like this:

+ +
<video src="rabbit320.webm" controls>
+  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.webm">link to the video</a> instead.</p>
+</video>
+ +

The features of note are:

+ +
+
{{htmlattrxref("src","video")}}
+
In the same way as for the {{htmlelement("img")}} element, the src (source) attribute contains a path to the video you want to embed. It works in exactly the same way.
+
{{htmlattrxref("controls","video")}}
+
Users must be able to control video and audio playback (it's especially critical for people who have epilepsy.) You must either use the controls attribute to include the browser's own control interface, or build your interface using the appropriate JavaScript API. At minimum, the interface must include a way to start and stop the media, and to adjust the volume.
+
The paragraph inside the <video> tags
+
This is called fallback content — this will be displayed if the browser accessing the page doesn't support the <video> element, allowing us to provide a fallback for older browsers. This can be anything you like; in this case we've provided a direct link to the video file, so the user can at least access it some way regardless of what browser they are using.
+
+ +

The embedded video will look something like this:

+ +

A simple video player showing a video of a small white rabbit

+ +

You can try the example live here (see also the source code.)

+ +

Suporte para múltiplos formatos

+ +

There's a problem with the above example, which you may have noticed already if you've tried to access the live link above with a browser like Safari or Internet Explorer. The video won't play! This is because different browsers support different video (and audio) formats.

+ +

Let's go through the terminology quickly. Formats like MP3, MP4 and WebM are called container formats. They contain different parts that make up the whole song or video — such as an audio track, a video track (in the case of video), and metadata to describe the media being presented.

+ +

The audio and video tracks are also in different formats, for example:

+ + + +

An audio player will tend to play an audio track directly, e.g. an MP3 or Ogg file. These don't need containers.

+ +
+

Nota: It is not quite that simple, as you can see from our audio-video codec compatibility table. In addition, many mobile platform browsers can play an unsupported format by handing it off to the underlying system's media player to play. But this will do for now.

+
+ +

The above formats exist to compress video and audio into manageable files (raw video and audio is very large). Browsers contain different {{Glossary("Codec","Codecs")}}, like Vorbis or H.264, which are used to convert the compressed sound and video into binary digits and back. As indicated above, browsers unfortunately don't all support the same codecs, so you will have to provide several files for each media production. If you're missing the right codec to decode the media, it just won't play.

+ +
+

Nota: You might be wondering why this situation exists. MP3 (for audio) and MP4/H.264 (for video) are both widely supported, and good quality. However, they are also patent encumbered — American patents cover MP3 until at least 2017, and H.264 until 2027 at the earliest, meaning that browsers that don't hold the patent have to pay huge sums of money to support these formats. In addition, many people avoid restricted software on principle, in favour of open formats. This is why we have to provide multiple formats for different browsers.

+
+ +

So how do we do this? Take a look at the following updated example (try it live here, also):

+ +
<video controls>
+  <source src="rabbit320.mp4" type="video/mp4">
+  <source src="rabbit320.webm" type="video/webm">
+  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
+</video>
+ +

Here we've taken the src attribute out of the actual <video> tag, and instead included separate {{htmlelement("source")}} elements that point to their own sources. In this case the browser will go through the <source> elements and play the first one that it has the codec to support. Including WebM and MP4 sources should be enough to play your video on most platforms and browsers these days.

+ +

Each <source> element also has a type attribute. This is optional, but it is advised that you include them — they contain the {{glossary("MIME type","MIME types")}} of the video files, and browsers can read these and immediately skip videos they don't understand. If they are not included, browsers will load and try to play each file until they find one that works, taking even more time and resources.

+ +
+

Nota: Our article on supported media formats contains some common {{glossary("MIME type","MIME types")}}.

+
+ +

Outras funcionalidades <video>

+ +

There are a number of other features you can include on an HTML5 video. Take a look at our third example, below:

+ +
<video controls width="400" height="400"
+       autoplay loop muted
+       poster="poster.png">
+  <source src="rabbit320.mp4" type="video/mp4">
+  <source src="rabbit320.webm" type="video/webm">
+  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
+</video>
+
+ +

This will give us a output looking something like this:

+ +

A video player showing a poster image before it plays. The poster image says HTML5 video example, OMG hell yeah!The new features are:

+ +
+
{{htmlattrxref("width","video")}} and {{htmlattrxref("height","video")}}
+
You can control the video size either with these attributes or with {{Glossary("CSS")}}. In both cases, videos maintain their native width-height ratio — known as the aspect ratio. If the aspect ratio is not maintained by the sizes you set, the video will grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default.
+
{{htmlattrxref("autoplay","video")}}
+
This attribute makes the audio or video start playing right away while the rest of the page is loading. You are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying.
+
{{htmlattrxref("loop","video")}}
+
This attribute makes the video (or audio) start playing again whenever it finishes. This can also be annoying, so only use if really necessary.
+
{{htmlattrxref("muted","video")}}
+
This attribute causes the media to play with the sound turned off by default.
+
{{htmlattrxref("poster","video")}}
+
This attribute takes as its value the URL of an image, which will be displayed before the video is played. It is intended to be used for a splash or advertising screen.
+
{{htmlattrxref("preload","video")}}
+
+

this attribute is used in the element for buffering large files. It can take one of 3 values:

+ +
    +
  • "none" does not buffer the file
  • +
  • "auto" buffers the media file
  • +
  • "metadata" buffers only the metadata for the file
  • +
+
+
+ +

You can find the above example available to play live on Github (also see the source code.) Note that we haven't included the autoplay attribute in the live version — if the video starts to play as soon as the page loads, you don't get to see the poster!

+ +

O elemento <audio>

+ +

The {{htmlelement("audio")}} element works in exactly the same way as the {{htmlelement("video")}} element, with a few small differences as outlined below. A typical example might look like so:

+ +
<audio controls>
+  <source src="viper.mp3" type="audio/mp3">
+  <source src="viper.ogg" type="audio/ogg">
+  <p>Your browser doesn't support HTML5 audio. Here is a <a href="viper.mp3">link to the audio</a> instead.</p>
+</audio>
+ +

This produces something like the following in a browser:

+ +

A simple audio player with a play button, timer, volume control, and progress bar

+ +
+

Nota: You can run the audio demo live on Github (also see the audio player source code.)

+
+ +

This takes up less space than a video player, as there is no visual component — you just need to display controls to play the audio. Other differences from HTML5 video are as follows:

+ + + +

Other than this, <audio> supports all the same features as <video> — review the above sections for more information about them.

+ +

Faixas de texto da exibição de vídeo

+ +

Now we'll discuss a slightly more advanced concept that is really useful to know about. Many people can't or don't want to hear the audio/video content they find on the Web, at least at certain times. For example:

+ + + +

Wouldn't it be nice to be able to provide these people with a transcript of the words being spoken in the audio/video? Well, thanks to HTML5 video you can, with the WebVTT format and the {{htmlelement("track")}} element.

+ +
+

Nota: "Transcribe" and "transcript" mean to write down spoken words as text.

+
+ +

WebVTT is a format for writing text files containing multiple strings of text along with metadata such as what time in the video you want each text string to be displayed, and even limited styling/positioning information. These text strings are called cues, and you can display different types for different purposes, the most common being:

+ +
+
subtitles
+
Translations of foreign material, for people who don't understand the words spoken in the audio.
+
captions
+
Synchronized transcriptions of dialog or descriptions of significant sounds, to let people who can't hear the audio understand what is going on.
+
timed descriptions
+
Text for conversion into audio, to serve people with visual impairments.
+
+ +

A typical WebVTT file will look something like this:

+ +
WEBVTT
+
+1
+00:00:22.230 --> 00:00:24.606
+This is the first subtitle.
+
+2
+00:00:30.739 --> 00:00:34.074
+This is the second.
+
+  ...
+
+ +

To get this displayed along with the HTML media playback, you need to:

+ +
    +
  1. Save it as a .vtt file in a sensible place.
  2. +
  3. Link to the .vtt file with the {{htmlelement("track")}} element. <track> should be placed within <audio> or <video>, but after all <source> elements. Use the {{htmlattrxref("kind","track")}} attribute to specify whether the cues are subtitles, captions, or descriptions. Further, use {{htmlattrxref("srclang","track")}} to tell the browser what language you have written the subtitles in.
  4. +
+ +

Here's an example:

+ +
<video controls>
+    <source src="example.mp4" type="video/mp4">
+    <source src="example.webm" type="video/webm">
+    <track kind="subtitles" src="subtitles_en.vtt" srclang="en">
+</video>
+ +

This will result in a video that has subtitles displayed, kind of like this:

+ +

Video player with stand controls such as play, stop, volume, and captions on and off. The video playing shows a scene of a man holding a spear-like weapon, and a caption reads "Esta hoja tiene pasado oscuro."

+ +

For more details, please read Adding captions and subtitles to HTML5 video. You can find the example that goes along with this article on Github, written by Ian Devlin (see the source code too.) This example uses some JavaScript to allow users to choose between different subtitles. Note that to turn the subtitles on, you need to press the "CC" button and select an option — English, Deutsch, or Español. 

+ +
+

Nota: Text tracks also help you with {{glossary("SEO")}}, since search engines especially thrive on text. Text tracks even allow search engines to link directly to a spot partway through the video.

+
+ +

Aprendizagem ativa: incorporar o seu próprio áudio e vídeo

+ +

For this active learning, we'd (ideally) like you to go out into the world and record some of your own video and audio — most phones these days allow you to record audio and video very easily, and provided you can transfer it on to your computer, you can use it. You may have to do some conversion to end up with a WebM and MP4 in the case of video, and an MP3 and Ogg in the case of audio, but there are enough programs out there to allow you to do this without too much trouble, such as Miro Video Converter and Audacity. We'd like you to have a go!

+ +

If you are unable to source any video or audio, then you can feel free to use our sample audio and video files to carry out this exercise. You can also use our sample code for reference.

+ +

We would like you to:

+ +
    +
  1. Save your audio and video files in a new directory on your computer.
  2. +
  3. Create a new HTML file in the same directory, called index.html.
  4. +
  5. Add <audio> and <video> elements to the page; make them display the default browser controls.
  6. +
  7. Give both of them <source> elements so that browsers will find the audio format they support best and load it. These should include type attributes.
  8. +
  9. Give the <video> element a poster that will be displayed before the video starts to be played. Have fun creating your own poster graphic.
  10. +
+ +

For an added bonus, you could try researching text tracks, and work out how to add some captions to your video.

+ +

Resumo

+ +

And that's a wrap; we hope you had fun playing with video and audio in web pages! In the next article, we'll look at other ways of embedding content on the Web, using technologies like {{htmlelement("iframe")}} and {{htmlelement("object")}}.

+ +

Consulte também

+ + + +

{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}

+ +
+
+ + + +
+ + + + + +
diff --git "a/files/pt-pt/learn/html/multimedia_e_integracao/conteudo_de_audio_e_v\303\255deo/index.html" "b/files/pt-pt/learn/html/multimedia_e_integracao/conteudo_de_audio_e_v\303\255deo/index.html" deleted file mode 100644 index 2ab6414459..0000000000 --- "a/files/pt-pt/learn/html/multimedia_e_integracao/conteudo_de_audio_e_v\303\255deo/index.html" +++ /dev/null @@ -1,369 +0,0 @@ ---- -title: Conteúdo de áudio e vídeo -slug: Learn/HTML/Multimedia_e_integracao/Conteudo_de_audio_e_vídeo -tags: - - Artigo - - Audio - - Guía - - HTML - - Principiante - - Video - - faixa - - legendas -translation_of: Learn/HTML/Multimedia_and_embedding/Video_and_audio_content ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}
- -

Now that we are comfortable with adding simple images to a webpage, the next step is to start adding video and audio players to your HTML documents! In this article we'll look at doing just that with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements; we'll then finish off by looking at how to add captions/subtitles to your videos.

- - - - - - - - - - - - -
Pré-requisitos:Basic computer literacy, basic software installed, basic knowledge of working with files, familiarity with HTML fundamentals (as covered in Getting started with HTML) and Images in HTML.
Objetivo:To learn how to embed video and audio content into a webpage, and add captions/subtitles to video.
- -

Áudio e vídeo na Web

- -

Web developers have wanted to use video and audio on the Web for a long time, ever since the early 2000s, when we started to have bandwidth fast enough to support any kind of video (video files are much larger than text or even images.) In the early days, native web technologies such as HTML didn't have the ability to embed video and audio on the Web, so proprietary (or plugin-based) technologies like Flash (and later, Silverlight) became popular for handling such content. This kind of technology worked ok, but it had a number of problems, including not working well with HTML/CSS features, security issues, and accessibility issues.

- -

A native solution would solve much of this if done right. Fortunately, a few years later the {{glossary("HTML5")}} specification had such features added, with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements, and some shiny new {{Glossary("JavaScript")}} {{Glossary("API","APIs")}} for controlling them. We'll not be looking at JavaScript here — just the basic foundations that can be achieved with HTML.

- -

We won't be teaching you how to produce audio and video files — that requires a completely different skillset. We have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own.

- -
-

Nota: Before you begin here, you should also know that there are a quite a few {{glossary("OVP","OVPs")}} (online video providers) like YouTube, Dailymotion, and Vimeo, and online audio providers like Soundcloud. Such companies offer a convenient, easy way to host and consume videos, so you don't have to worry about the enormous bandwidth consumption. OVPs even usually offer ready-made code for embedding video/audio in your webpages. If you go that route, you can avoid some of the difficulties we discuss in this article. We'll be discussing this kind of service a bit more in the next article.

-
- -

O elemento <video>

- -

The {{htmlelement("video")}} element allows you to embed a video very easily. A really simple example looks like this:

- -
<video src="rabbit320.webm" controls>
-  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.webm">link to the video</a> instead.</p>
-</video>
- -

The features of note are:

- -
-
{{htmlattrxref("src","video")}}
-
In the same way as for the {{htmlelement("img")}} element, the src (source) attribute contains a path to the video you want to embed. It works in exactly the same way.
-
{{htmlattrxref("controls","video")}}
-
Users must be able to control video and audio playback (it's especially critical for people who have epilepsy.) You must either use the controls attribute to include the browser's own control interface, or build your interface using the appropriate JavaScript API. At minimum, the interface must include a way to start and stop the media, and to adjust the volume.
-
The paragraph inside the <video> tags
-
This is called fallback content — this will be displayed if the browser accessing the page doesn't support the <video> element, allowing us to provide a fallback for older browsers. This can be anything you like; in this case we've provided a direct link to the video file, so the user can at least access it some way regardless of what browser they are using.
-
- -

The embedded video will look something like this:

- -

A simple video player showing a video of a small white rabbit

- -

You can try the example live here (see also the source code.)

- -

Suporte para múltiplos formatos

- -

There's a problem with the above example, which you may have noticed already if you've tried to access the live link above with a browser like Safari or Internet Explorer. The video won't play! This is because different browsers support different video (and audio) formats.

- -

Let's go through the terminology quickly. Formats like MP3, MP4 and WebM are called container formats. They contain different parts that make up the whole song or video — such as an audio track, a video track (in the case of video), and metadata to describe the media being presented.

- -

The audio and video tracks are also in different formats, for example:

- - - -

An audio player will tend to play an audio track directly, e.g. an MP3 or Ogg file. These don't need containers.

- -
-

Nota: It is not quite that simple, as you can see from our audio-video codec compatibility table. In addition, many mobile platform browsers can play an unsupported format by handing it off to the underlying system's media player to play. But this will do for now.

-
- -

The above formats exist to compress video and audio into manageable files (raw video and audio is very large). Browsers contain different {{Glossary("Codec","Codecs")}}, like Vorbis or H.264, which are used to convert the compressed sound and video into binary digits and back. As indicated above, browsers unfortunately don't all support the same codecs, so you will have to provide several files for each media production. If you're missing the right codec to decode the media, it just won't play.

- -
-

Nota: You might be wondering why this situation exists. MP3 (for audio) and MP4/H.264 (for video) are both widely supported, and good quality. However, they are also patent encumbered — American patents cover MP3 until at least 2017, and H.264 until 2027 at the earliest, meaning that browsers that don't hold the patent have to pay huge sums of money to support these formats. In addition, many people avoid restricted software on principle, in favour of open formats. This is why we have to provide multiple formats for different browsers.

-
- -

So how do we do this? Take a look at the following updated example (try it live here, also):

- -
<video controls>
-  <source src="rabbit320.mp4" type="video/mp4">
-  <source src="rabbit320.webm" type="video/webm">
-  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
-</video>
- -

Here we've taken the src attribute out of the actual <video> tag, and instead included separate {{htmlelement("source")}} elements that point to their own sources. In this case the browser will go through the <source> elements and play the first one that it has the codec to support. Including WebM and MP4 sources should be enough to play your video on most platforms and browsers these days.

- -

Each <source> element also has a type attribute. This is optional, but it is advised that you include them — they contain the {{glossary("MIME type","MIME types")}} of the video files, and browsers can read these and immediately skip videos they don't understand. If they are not included, browsers will load and try to play each file until they find one that works, taking even more time and resources.

- -
-

Nota: Our article on supported media formats contains some common {{glossary("MIME type","MIME types")}}.

-
- -

Outras funcionalidades <video>

- -

There are a number of other features you can include on an HTML5 video. Take a look at our third example, below:

- -
<video controls width="400" height="400"
-       autoplay loop muted
-       poster="poster.png">
-  <source src="rabbit320.mp4" type="video/mp4">
-  <source src="rabbit320.webm" type="video/webm">
-  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
-</video>
-
- -

This will give us a output looking something like this:

- -

A video player showing a poster image before it plays. The poster image says HTML5 video example, OMG hell yeah!The new features are:

- -
-
{{htmlattrxref("width","video")}} and {{htmlattrxref("height","video")}}
-
You can control the video size either with these attributes or with {{Glossary("CSS")}}. In both cases, videos maintain their native width-height ratio — known as the aspect ratio. If the aspect ratio is not maintained by the sizes you set, the video will grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default.
-
{{htmlattrxref("autoplay","video")}}
-
This attribute makes the audio or video start playing right away while the rest of the page is loading. You are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying.
-
{{htmlattrxref("loop","video")}}
-
This attribute makes the video (or audio) start playing again whenever it finishes. This can also be annoying, so only use if really necessary.
-
{{htmlattrxref("muted","video")}}
-
This attribute causes the media to play with the sound turned off by default.
-
{{htmlattrxref("poster","video")}}
-
This attribute takes as its value the URL of an image, which will be displayed before the video is played. It is intended to be used for a splash or advertising screen.
-
{{htmlattrxref("preload","video")}}
-
-

this attribute is used in the element for buffering large files. It can take one of 3 values:

- -
    -
  • "none" does not buffer the file
  • -
  • "auto" buffers the media file
  • -
  • "metadata" buffers only the metadata for the file
  • -
-
-
- -

You can find the above example available to play live on Github (also see the source code.) Note that we haven't included the autoplay attribute in the live version — if the video starts to play as soon as the page loads, you don't get to see the poster!

- -

O elemento <audio>

- -

The {{htmlelement("audio")}} element works in exactly the same way as the {{htmlelement("video")}} element, with a few small differences as outlined below. A typical example might look like so:

- -
<audio controls>
-  <source src="viper.mp3" type="audio/mp3">
-  <source src="viper.ogg" type="audio/ogg">
-  <p>Your browser doesn't support HTML5 audio. Here is a <a href="viper.mp3">link to the audio</a> instead.</p>
-</audio>
- -

This produces something like the following in a browser:

- -

A simple audio player with a play button, timer, volume control, and progress bar

- -
-

Nota: You can run the audio demo live on Github (also see the audio player source code.)

-
- -

This takes up less space than a video player, as there is no visual component — you just need to display controls to play the audio. Other differences from HTML5 video are as follows:

- - - -

Other than this, <audio> supports all the same features as <video> — review the above sections for more information about them.

- -

Faixas de texto da exibição de vídeo

- -

Now we'll discuss a slightly more advanced concept that is really useful to know about. Many people can't or don't want to hear the audio/video content they find on the Web, at least at certain times. For example:

- - - -

Wouldn't it be nice to be able to provide these people with a transcript of the words being spoken in the audio/video? Well, thanks to HTML5 video you can, with the WebVTT format and the {{htmlelement("track")}} element.

- -
-

Nota: "Transcribe" and "transcript" mean to write down spoken words as text.

-
- -

WebVTT is a format for writing text files containing multiple strings of text along with metadata such as what time in the video you want each text string to be displayed, and even limited styling/positioning information. These text strings are called cues, and you can display different types for different purposes, the most common being:

- -
-
subtitles
-
Translations of foreign material, for people who don't understand the words spoken in the audio.
-
captions
-
Synchronized transcriptions of dialog or descriptions of significant sounds, to let people who can't hear the audio understand what is going on.
-
timed descriptions
-
Text for conversion into audio, to serve people with visual impairments.
-
- -

A typical WebVTT file will look something like this:

- -
WEBVTT
-
-1
-00:00:22.230 --> 00:00:24.606
-This is the first subtitle.
-
-2
-00:00:30.739 --> 00:00:34.074
-This is the second.
-
-  ...
-
- -

To get this displayed along with the HTML media playback, you need to:

- -
    -
  1. Save it as a .vtt file in a sensible place.
  2. -
  3. Link to the .vtt file with the {{htmlelement("track")}} element. <track> should be placed within <audio> or <video>, but after all <source> elements. Use the {{htmlattrxref("kind","track")}} attribute to specify whether the cues are subtitles, captions, or descriptions. Further, use {{htmlattrxref("srclang","track")}} to tell the browser what language you have written the subtitles in.
  4. -
- -

Here's an example:

- -
<video controls>
-    <source src="example.mp4" type="video/mp4">
-    <source src="example.webm" type="video/webm">
-    <track kind="subtitles" src="subtitles_en.vtt" srclang="en">
-</video>
- -

This will result in a video that has subtitles displayed, kind of like this:

- -

Video player with stand controls such as play, stop, volume, and captions on and off. The video playing shows a scene of a man holding a spear-like weapon, and a caption reads "Esta hoja tiene pasado oscuro."

- -

For more details, please read Adding captions and subtitles to HTML5 video. You can find the example that goes along with this article on Github, written by Ian Devlin (see the source code too.) This example uses some JavaScript to allow users to choose between different subtitles. Note that to turn the subtitles on, you need to press the "CC" button and select an option — English, Deutsch, or Español. 

- -
-

Nota: Text tracks also help you with {{glossary("SEO")}}, since search engines especially thrive on text. Text tracks even allow search engines to link directly to a spot partway through the video.

-
- -

Aprendizagem ativa: incorporar o seu próprio áudio e vídeo

- -

For this active learning, we'd (ideally) like you to go out into the world and record some of your own video and audio — most phones these days allow you to record audio and video very easily, and provided you can transfer it on to your computer, you can use it. You may have to do some conversion to end up with a WebM and MP4 in the case of video, and an MP3 and Ogg in the case of audio, but there are enough programs out there to allow you to do this without too much trouble, such as Miro Video Converter and Audacity. We'd like you to have a go!

- -

If you are unable to source any video or audio, then you can feel free to use our sample audio and video files to carry out this exercise. You can also use our sample code for reference.

- -

We would like you to:

- -
    -
  1. Save your audio and video files in a new directory on your computer.
  2. -
  3. Create a new HTML file in the same directory, called index.html.
  4. -
  5. Add <audio> and <video> elements to the page; make them display the default browser controls.
  6. -
  7. Give both of them <source> elements so that browsers will find the audio format they support best and load it. These should include type attributes.
  8. -
  9. Give the <video> element a poster that will be displayed before the video starts to be played. Have fun creating your own poster graphic.
  10. -
- -

For an added bonus, you could try researching text tracks, and work out how to add some captions to your video.

- -

Resumo

- -

And that's a wrap; we hope you had fun playing with video and audio in web pages! In the next article, we'll look at other ways of embedding content on the Web, using technologies like {{htmlelement("iframe")}} and {{htmlelement("object")}}.

- -

Consulte também

- - - -

{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}

- -
-
- - - -
- - - - - -
diff --git a/files/pt-pt/learn/html/multimedia_e_integracao/index.html b/files/pt-pt/learn/html/multimedia_e_integracao/index.html deleted file mode 100644 index 724e0ca3f5..0000000000 --- a/files/pt-pt/learn/html/multimedia_e_integracao/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Multimédia e integração -slug: Learn/HTML/Multimedia_e_integracao -tags: - - Aprender - - Audio - - Avaliação - - CodingScripting - - Flash - - Guía - - HTML - - Imagens - - Landing - - Principiante - - Responsivo - - SVG - - Video - - iframes - - mapas de imagem -translation_of: Learn/HTML/Multimedia_and_embedding ---- -

{{LearnSidebar}}

- -

Nós já vimos muito texto até agora neste curso, mas a Web seria realmente chata se se utilizasse apenas texto. Vamos começar a ver como dar vida à Web, com conteúdo mais interessante! Este módulo explora como utilizar HTML para incluir multimédia nas suas páginas da Web, incluindo os modos diferentes em que as imagens podem ser incluídas, e como incorporar vídeo, áudio e até páginas da Web completas.

- -

Pré-requisitos

- -

Antes de iniciar este módulo, deverá ter um conhecimento razoável dos conceitos básicos de HTML, como anteriormente abordado em Introdução ao HTML. Se ainda não leu este módulo (ou qualquer coisa similar), leia-o primeiro, e depois volte aqui!

- -
-

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

-
- -

Guias

- -

This module contains the following articles, which will take you through all the fundamentals of embedding multimedia on webpages.

- -
-
Imagens em HTML
-
There are other types of multimedia to consider, but it is logical to start with the humble {{htmlelement("img")}} element, used to embed a simple image in a webpage. In this article we'll look at how to use it in more depth, including basics, annotating it with captions using {{htmlelement("figure")}}, and how it relates to CSS background images.
-
Conteúdo de vídeo e de áudio
-
Next, we'll look at how to use the HTML5 {{htmlelement("video")}} and {{htmlelement("audio")}} elements, to embed video and audio on our pages; including basics, providing access to different file formats to different browsers, adding captions and subtitles, and how to add fallbacks for older browsers.
-
De <object> para <iframe> — outras tecnologias de integração
-
At this point we'd like to take somewhat of a sideways step, looking at a couple of elements that allow you to embed a wide variety of content types into your webpages: the {{htmlelement("iframe")}}, {{htmlelement("embed")}} and {{htmlelement("object")}} elements. <iframe>s are for embedding other web pages, and the other two allow you to embed PDFs, SVG, and even Flash — a technology on its way out, but which you may still see semi-regularly.
-
Adicionar gráficos de vetor à Web
-
Vector graphics can be very useful in certain situations. Unlike regular formats like PNG/JPG, they don't distort/pixelate when zoomed in — they can remain smooth when scaled. This article introduces you to what vector graphics are, and how to include the popular {{glossary("SVG")}} format in web pages.
-
Imagens responsivas
-
With so many different device types now able to browse the Web — from mobile phones to desktop computers — an essential concept to master in the modern web world is responsive design. This refers to the creation of webpages that can automatically change their features to suit different screen sizes, resolutions, etc. This will be looked at in much more detail in a CSS module later on, but for now we'll look at the tools HTML has available to create responsive images, including the {{htmlelement("picture")}} element.
-
- -

Avaliações

- -

The following assessments will test your understanding of the HTML basics covered in the guides above:

- -
-
Página de boas-vindas da Mozilla
-
In this assessment, we'll test your knowledge of some of the techniques discussed in this module's articles, getting you to add some images and video to a funky splash page all about Mozilla!
-
- -

Consulte também

- -
-
Adicionar um mapa clicável no topo de uma imagem
-
Image maps provide a mechanism to make different parts of an image link to different places (think of a map, linking through to further information about each different country you click on.) This technique can sometimes be useful.
-
Literacia da Web - básicos 2
-
-

An excellent Mozilla foundation course that explores and tests some of the skills talked about in the Multimedia and embedding module. Dive deeper into the basics of composing webpages, designing for accessibility, sharing resources, using online media, and working open (meaning that your content is freely available, and shareable by others).

-
-
diff --git a/files/pt-pt/learn/html/tables/advanced/index.html b/files/pt-pt/learn/html/tables/advanced/index.html new file mode 100644 index 0000000000..79f6bf801b --- /dev/null +++ b/files/pt-pt/learn/html/tables/advanced/index.html @@ -0,0 +1,538 @@ +--- +title: HTML - funcionalidades avançadas de tabela e acessibilidade +slug: Learn/HTML/Tables/Avancada +tags: + - Acessibilidade + - Aprender + - Artigo + - Avançado + - Cabeçalhos + - HTML + - Headers + - Principiante + - Resumo + - caption + - incorporar + - legenda + - tabela +translation_of: Learn/HTML/Tables/Advanced +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Tables/Basics", "Learn/HTML/Tables/Structuring_planet_data", "Learn/HTML/Tables")}}
+ +

No segundo artigo neste módulo, nós vamos ver algumas funcionalidades mais avançadas das tabelas HTML tables — tais como legendas/resumos e agrupar as suas filas no cabçalho da taela, secções de corpo e rodapé — bem como, ver a acessibilidade das tabelas para os utilizadores deficientes visuais.

+ + + + + + + + + + + + +
Pré-requisitos:The basics of HTML (see Introduction to HTML).
Objetivo:To learn about more advanced HTML table features, and the accessibility of tables.
+ +

Adicionar uma legenda à sua tabela com <caption>

+ +

You can give your table a caption by putting it inside a {{htmlelement("caption")}} element and nesting that inside the {{htmlelement("table")}} element. You should put it just below the opening <table> tag.

+ +
<table>
+  <caption>Dinosaurs in the Jurassic period</caption>
+
+  ...
+</table>
+ +

As you can infer from the brief example above, the caption is meant to contain a description of the table contents. This is useful for all readers wishing to get a quick idea of whether the table is useful to them as they scan the page, but particularly for blind users. Rather than have a screenreader read out the contents of many cells just to find out what the table is about, he or she can rely on a caption and then decide whether or not to read the table in greater detail.

+ +

A caption is placed directly beneath the <table> tag.

+ +
+

Nota: The {{htmlattrxref("summary","table")}} attribute can also be used on the <table> element to provide a description — this is also read out by screenreaders. We'd recommend using the <caption> element instead, however, as summary is {{glossary("deprecated")}} by the HTML5 spec, and can't be read by sighted users (it doesn't appear on the page.)

+
+ +

Aprendizagem ativa: Adicionar uma caption

+ +

Let's try this out, revisiting an example we first met in the previous article.

+ +
    +
  1. Open up your language teacher's school timetable from the end of HTML Table Basics, or make a local copy of our timetable-fixed.html file.
  2. +
  3. Add a suitable caption for the table.
  4. +
  5. Save your code and open it in a browser to see what it looks like.
  6. +
+ +
+

Nota: You can find our version on GitHub — see timetable-caption.html (see it live also).

+
+ +

Adding structure with <thead>, <tfoot>, and <tbody>

+ +

As your tables get a bit more complex in structure, it is useful to give them more structural definition. One clear way to do this is by using {{htmlelement("thead")}}, {{htmlelement("tfoot")}}, and {{htmlelement("tbody")}}, which allow you to mark up a header, footer, and body section for the table.

+ +

These elements don't make the table any more accessible to screenreader users, and don't result in any visual enhancement on their own. They are however very useful for styling and layout — acting as useful hooks for adding CSS to your table. To give you some interesting examples, in the case of a long table you could make the table header and footer repeat on every printed page, and you could make the table body display on a single page and have the contents available by scrolling up and down.

+ +

To use them:

+ + + +
+

Note: <tbody> is always included in every table, implicitly if you don't specify it in your code. To check this, open up one of your previous examples that doesn't include <tbody> and look at the HTML code in your browser developer tools — you will see that the browser has added this tag for you. You might wonder why you ought to bother including it at all — you should, because it gives you more control over your table structure and styling.

+
+ +

Aprendizagem ativa: Adicionar uma estrutura de tabela

+ +

Let's put these new elements into action.

+ +
    +
  1. First of all, make a local copy of spending-record.html and minimal-table.css in a new folder.
  2. +
  3. Try opening it in a browser — You'll see that it looks OK, but it could stand to be improved. The "SUM" row that contains a summation of the spent amounts seems to be in the wrong place, and there are some details missing from the code.
  4. +
  5. Put the obvious headers row inside a <thead> element, the "SUM" row inside a <tfoot> element, and the rest of the content inside a <tbody> element.
  6. +
  7. Save and refresh, and you'll see that adding the <tfoot> element has caused the "SUM" row to go down to the bottom of the table.
  8. +
  9. Next, add a {{htmlattrxref("colspan","td")}} attribute to make the "SUM" cell span across the first four columns, so the actual number appears at the bottom of the "Cost" column.
  10. +
  11. Let's add some simple extra styling to the table, to give you an idea of how useful these elements are for applying CSS. Inside the head of your HTML document, you'll see an empty {{htmlelement("style")}} element. Inside this element, add the following lines of CSS code: +
    tbody {
    +  font-size: 90%;
    +  font-style: italic;
    +}
    +
    +tfoot {
    +  font-weight: bold;
    +}
    +
    +
  12. +
  13. Save and refresh, and have a look at the result. If the <tbody> and <tfoot> elements weren't in place, you'd have to write much more complicated selectors/rules to apply the same styling.
  14. +
+ +
+

Nota: We don't expect you to fully understand the CSS right now. You'll learn more about this when you go through our CSS modules (Introduction to CSS is a good place to start; we also have an article specifically on styling tables).

+
+ +

Your finished table should look something like the following:

+ + + +

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

+ +
+

Nota: You can also find it on Github as spending-record-finished.html (see it live also).

+
+ +

Incorporar Tabelas

+ +

It is possible to nest a table inside another one, as long as you include the complete structure, including the <table> element. This is generally not really advised, as it makes the markup more confusing and less accessible to screenreader users, and in many cases you might as well just insert extra cells/rows/columns into the existing table. It is however sometimes necessary, for example if you want to import content easily from other sources.

+ +

The following markup shows a simple nested table:

+ +
<table id="table1">
+  <tr>
+    <th>title1</th>
+    <th>title2</th>
+    <th>title3</th>
+  </tr>
+  <tr>
+    <td id="nested">
+      <table id="table2">
+        <tr>
+          <td>cell1</td>
+          <td>cell2</td>
+          <td>cell3</td>
+        </tr>
+      </table>
+    </td>
+    <td>cell2</td>
+    <td>cell3</td>
+  </tr>
+  <tr>
+    <td>cell4</td>
+    <td>cell5</td>
+    <td>cell6</td>
+  </tr>
+</table>
+ +

The output of which looks something like this:

+ + + + + + + + + + + + + + + + + + + +
title1title2title3
+ + + + + + + + +
cell1cell2cell3
+
cell2cell3
cell4cell5cell6
+ +

Tabelas para utilizadores deficientes visuais

+ +

Let's recap briefly on how we use data tables. A table can be a handy tool, for giving us quick access to data and allowing us to look up different values. For example, It takes only a short glance at the table below to find out how many rings were sold in Gent last August. To understand its information we make visual associations between the data in this table and its column and/or row headers.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Items Sold August 2016
  ClothesAccessories
  TrousersSkirtsDressesBraceletsRings
BelgiumAntwerp5622437223
Gent4618506115
Brussels5127386928
The NetherlandsAmsterdam8934698538
Utrecht8012433619
+ +

But what if you cannot make those visual associations? How then can you read a table like the above? Visually impaired people often use a screenreader that reads out information on web pages to them. This is no problem when you're reading plain text but interpreting a table can be quite a challenge for a blind person. Nevertheless, with the proper markup we can replace visual associations by programmatic ones.

+ +

This section of the article provides further techniques for making tables as accessible as possible.

+ +

Utilizar os cabeçalhos de coluna e linha

+ +

Screenreaders will identify all headers and use them to make programmatic associations between those headers and the cells they relate to. The combination of column and row headers will identify and interpret the data in each cell so that screenreader user can interpret the table similarly to how a sighted user does.

+ +

We already covered headers in our previous article — see Adding headers with <th> elements.

+ +

O atributo de scope

+ +

A new topic for this article is the {{htmlattrxref("scope","th")}} attribute, which can be added to the <th> element to tell screenreaders exactly what cells the header is a header for — is it a header for the row it is in, or the column, for example? Looking back to our spending record example from earlier on, you could unambiguously define the column headers as column headers like this:

+ +
<thead>
+  <tr>
+    <th scope="col">Purchase</th>
+    <th scope="col">Location</th>
+    <th scope="col">Date</th>
+    <th scope="col">Evaluation</th>
+    <th scope="col">Cost (€)</th>
+  </tr>
+</thead>
+ +

And each row could have a header defined like this (if we added row headers as well as column headers):

+ +
<tr>
+  <th scope="row">Haircut</th>
+  <td>Hairdresser</td>
+  <td>12/09</td>
+  <td>Great idea</td>
+  <td>30</td>
+</tr>
+ +

Screenreaders will recognize markup structured like this, and allow their users to read out the entire column or row at once, for example.

+ +

scope has two more possible values — colgroup and rowgroup. these are used for headings that sit over the top of multiple columns or rows. If you look back at the "Items sold..." table at the start of this section of the article, you'll see that the "Clothes" cell sits above the "Trousers", "Skirts", and "Dresses" cells. All of these cells should be marked up as headers (<th>), but "Clothes" is a heading that sits over the top and defines the other three subheadings. "Clothes" therefore should get an attribute of scope="colgroup", whereas the others would get an attribute of scope="col".

+ +

A identificação e atributos de cabeçalhos

+ +

An alternative to using the scope attribute is to use {{htmlattrxref("id")}} and {{htmlattrxref("headers", "td")}} attributes to create associations between headers and cells. The way they are used is as follows:

+ +
    +
  1. You add a unique id to each <th> element.
  2. +
  3. You add a headers attribute to each <td> element. Each headers attribute has to contain a list of the ids of all the <th> elements that act as a header for that cell, separated by spaces.
  4. +
+ +

This gives your HTML table an explicit definition of the position of each cell in the table, defined by the header(s) for each column and row it is part of, kind of like a spreadsheet. For it to work well, the table really needs both column and row headers.

+ +

Returning to our spending costs example, the previous two snippets could be rewritten like this:

+ +
<thead>
+  <tr>
+    <th id="purchase">Purchase</th>
+    <th id="location">Location</th>
+    <th id="date">Date</th>
+    <th id="evaluation">Evaluation</th>
+    <th id="cost">Cost (€)</th>
+  </tr>
+</thead>
+<tbody>
+<tr>
+  <th id="haircut">Haircut</th>
+  <td headers="location haircut">Hairdresser</td>
+  <td headers="date haircut">12/09</td>
+  <td headers="evaluation haircut">Great idea</td>
+  <td headers="cost haircut">30</td>
+</tr>
+
+  ...
+
+</tbody>
+ +
+

Nota: This method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for errors.  The scope approach is usually enough for most tables.

+
+ +

Aprendizagem ativa: manipular scope e cabeçalhos

+ +
    +
  1. For this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a new directory.
  2. +
  3. Now try adding in the appropriate scope attributes to make this table more appropriate.
  4. +
  5. Finally, try making another copy of the starter files, and this time make the table more accessible using id and headers attributes.
  6. +
+ +
+

Nota: You can check your work against our finished examples — see items-sold-scope.html (also see this live) and items-sold-headers.html (see this live too).

+
+ +

Resumo

+ +

There are a few other things you could learn about table HTML, but we have really given all you need to know at this moment in time. At this point, you might want to go and learn about styling HTML tables — see Styling Tables.

+ +
{{PreviousMenuNext("Learn/HTML/Tables/Basics", "Learn/HTML/Tables/Structuring_planet_data", "Learn/HTML/Tables")}}
+ +
+ + + + + +
diff --git a/files/pt-pt/learn/html/tables/avaliacao_estruturar_os_dados_dos_planetas/index.html b/files/pt-pt/learn/html/tables/avaliacao_estruturar_os_dados_dos_planetas/index.html deleted file mode 100644 index 70fbf3601a..0000000000 --- a/files/pt-pt/learn/html/tables/avaliacao_estruturar_os_dados_dos_planetas/index.html +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: 'Avaliação: Estruturar os dados dos planetas' -slug: Learn/HTML/Tables/Avaliacao_Estruturar_os_dados_dos_planetas -translation_of: Learn/HTML/Tables/Structuring_planet_data ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
- -

Na nossa avaliação de tabela, nós forncemos-lhe alguns dados dos planetas no nosso sistema solar, para que possa estruturá-los numa tabela HTML .

- - - - - - - - - - - - -
Pré-requisitos:Before attempting this assessment you should have already worked through all the articles in this module.
Objetivo:To test comprehension of HTML tables and associated features.
- -

Ponto inicial

- -

To get this assessment started, make local copies of blank-template.html, minimal-table.css, and planets-data.txt in a new directory in your local computer.

- -
-

Note: Alternatively, you could use a site like JSBin or Thimble to do your assessment. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have separate JavaScript/CSS panels, feel free to put them inline <script>/<style> elements inside the HTML page.

-
- -

Sumário do projeto

- -

You are working at a school; currently your students are studying the planets of our solar system, and you want to provide them with an easy-to-follow set of data to look up facts and figures about the planets. An HTML data table would be ideal — you need to take the raw data you have available and turn it into a table, following the steps below.

- -

The finished table should look like this:

- -

- -

You can also see the example live here (no looking at the source code — don't cheat!)

- - - -

Passos para concluir

- -

The following steps describe what you need to do to complete the table example. All the data you'll need is contained in the planets-data.txt file. If you have trouble visualising the data, look at the live example above, or try drawing a diagram.

- -
    -
  1. Open your copy of blank-template.html, and start the table off by giving it an outer container, a table header, and a table body. You don't need a table footer for this example.
  2. -
  3. Add the provided caption to your table.
  4. -
  5. Add a row to the table header containing all the column headers.
  6. -
  7. Create all the content rows inside the table body, remembering to make all the row headings into headings semantically.
  8. -
  9. Make sure all the content is inserted into the right cells — in the raw data, each row of planet data is shown next to its associated planet.
  10. -
  11. Add attributes to make the row and column headers unambiguously associated with the rows, columns, or rowgroups that they act as headings for.
  12. -
  13. Add a black border just around the column that contains all the planet name row headers.
  14. -
- -

Dicas e sugestões

- - - -

Avaliação

- -

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the Learning Area Discourse thread, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

- -

{{PreviousMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}

- -
- - - - - -
diff --git a/files/pt-pt/learn/html/tables/avancada/index.html b/files/pt-pt/learn/html/tables/avancada/index.html deleted file mode 100644 index 79f6bf801b..0000000000 --- a/files/pt-pt/learn/html/tables/avancada/index.html +++ /dev/null @@ -1,538 +0,0 @@ ---- -title: HTML - funcionalidades avançadas de tabela e acessibilidade -slug: Learn/HTML/Tables/Avancada -tags: - - Acessibilidade - - Aprender - - Artigo - - Avançado - - Cabeçalhos - - HTML - - Headers - - Principiante - - Resumo - - caption - - incorporar - - legenda - - tabela -translation_of: Learn/HTML/Tables/Advanced ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Tables/Basics", "Learn/HTML/Tables/Structuring_planet_data", "Learn/HTML/Tables")}}
- -

No segundo artigo neste módulo, nós vamos ver algumas funcionalidades mais avançadas das tabelas HTML tables — tais como legendas/resumos e agrupar as suas filas no cabçalho da taela, secções de corpo e rodapé — bem como, ver a acessibilidade das tabelas para os utilizadores deficientes visuais.

- - - - - - - - - - - - -
Pré-requisitos:The basics of HTML (see Introduction to HTML).
Objetivo:To learn about more advanced HTML table features, and the accessibility of tables.
- -

Adicionar uma legenda à sua tabela com <caption>

- -

You can give your table a caption by putting it inside a {{htmlelement("caption")}} element and nesting that inside the {{htmlelement("table")}} element. You should put it just below the opening <table> tag.

- -
<table>
-  <caption>Dinosaurs in the Jurassic period</caption>
-
-  ...
-</table>
- -

As you can infer from the brief example above, the caption is meant to contain a description of the table contents. This is useful for all readers wishing to get a quick idea of whether the table is useful to them as they scan the page, but particularly for blind users. Rather than have a screenreader read out the contents of many cells just to find out what the table is about, he or she can rely on a caption and then decide whether or not to read the table in greater detail.

- -

A caption is placed directly beneath the <table> tag.

- -
-

Nota: The {{htmlattrxref("summary","table")}} attribute can also be used on the <table> element to provide a description — this is also read out by screenreaders. We'd recommend using the <caption> element instead, however, as summary is {{glossary("deprecated")}} by the HTML5 spec, and can't be read by sighted users (it doesn't appear on the page.)

-
- -

Aprendizagem ativa: Adicionar uma caption

- -

Let's try this out, revisiting an example we first met in the previous article.

- -
    -
  1. Open up your language teacher's school timetable from the end of HTML Table Basics, or make a local copy of our timetable-fixed.html file.
  2. -
  3. Add a suitable caption for the table.
  4. -
  5. Save your code and open it in a browser to see what it looks like.
  6. -
- -
-

Nota: You can find our version on GitHub — see timetable-caption.html (see it live also).

-
- -

Adding structure with <thead>, <tfoot>, and <tbody>

- -

As your tables get a bit more complex in structure, it is useful to give them more structural definition. One clear way to do this is by using {{htmlelement("thead")}}, {{htmlelement("tfoot")}}, and {{htmlelement("tbody")}}, which allow you to mark up a header, footer, and body section for the table.

- -

These elements don't make the table any more accessible to screenreader users, and don't result in any visual enhancement on their own. They are however very useful for styling and layout — acting as useful hooks for adding CSS to your table. To give you some interesting examples, in the case of a long table you could make the table header and footer repeat on every printed page, and you could make the table body display on a single page and have the contents available by scrolling up and down.

- -

To use them:

- - - -
-

Note: <tbody> is always included in every table, implicitly if you don't specify it in your code. To check this, open up one of your previous examples that doesn't include <tbody> and look at the HTML code in your browser developer tools — you will see that the browser has added this tag for you. You might wonder why you ought to bother including it at all — you should, because it gives you more control over your table structure and styling.

-
- -

Aprendizagem ativa: Adicionar uma estrutura de tabela

- -

Let's put these new elements into action.

- -
    -
  1. First of all, make a local copy of spending-record.html and minimal-table.css in a new folder.
  2. -
  3. Try opening it in a browser — You'll see that it looks OK, but it could stand to be improved. The "SUM" row that contains a summation of the spent amounts seems to be in the wrong place, and there are some details missing from the code.
  4. -
  5. Put the obvious headers row inside a <thead> element, the "SUM" row inside a <tfoot> element, and the rest of the content inside a <tbody> element.
  6. -
  7. Save and refresh, and you'll see that adding the <tfoot> element has caused the "SUM" row to go down to the bottom of the table.
  8. -
  9. Next, add a {{htmlattrxref("colspan","td")}} attribute to make the "SUM" cell span across the first four columns, so the actual number appears at the bottom of the "Cost" column.
  10. -
  11. Let's add some simple extra styling to the table, to give you an idea of how useful these elements are for applying CSS. Inside the head of your HTML document, you'll see an empty {{htmlelement("style")}} element. Inside this element, add the following lines of CSS code: -
    tbody {
    -  font-size: 90%;
    -  font-style: italic;
    -}
    -
    -tfoot {
    -  font-weight: bold;
    -}
    -
    -
  12. -
  13. Save and refresh, and have a look at the result. If the <tbody> and <tfoot> elements weren't in place, you'd have to write much more complicated selectors/rules to apply the same styling.
  14. -
- -
-

Nota: We don't expect you to fully understand the CSS right now. You'll learn more about this when you go through our CSS modules (Introduction to CSS is a good place to start; we also have an article specifically on styling tables).

-
- -

Your finished table should look something like the following:

- - - -

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

- -
-

Nota: You can also find it on Github as spending-record-finished.html (see it live also).

-
- -

Incorporar Tabelas

- -

It is possible to nest a table inside another one, as long as you include the complete structure, including the <table> element. This is generally not really advised, as it makes the markup more confusing and less accessible to screenreader users, and in many cases you might as well just insert extra cells/rows/columns into the existing table. It is however sometimes necessary, for example if you want to import content easily from other sources.

- -

The following markup shows a simple nested table:

- -
<table id="table1">
-  <tr>
-    <th>title1</th>
-    <th>title2</th>
-    <th>title3</th>
-  </tr>
-  <tr>
-    <td id="nested">
-      <table id="table2">
-        <tr>
-          <td>cell1</td>
-          <td>cell2</td>
-          <td>cell3</td>
-        </tr>
-      </table>
-    </td>
-    <td>cell2</td>
-    <td>cell3</td>
-  </tr>
-  <tr>
-    <td>cell4</td>
-    <td>cell5</td>
-    <td>cell6</td>
-  </tr>
-</table>
- -

The output of which looks something like this:

- - - - - - - - - - - - - - - - - - - -
title1title2title3
- - - - - - - - -
cell1cell2cell3
-
cell2cell3
cell4cell5cell6
- -

Tabelas para utilizadores deficientes visuais

- -

Let's recap briefly on how we use data tables. A table can be a handy tool, for giving us quick access to data and allowing us to look up different values. For example, It takes only a short glance at the table below to find out how many rings were sold in Gent last August. To understand its information we make visual associations between the data in this table and its column and/or row headers.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Items Sold August 2016
  ClothesAccessories
  TrousersSkirtsDressesBraceletsRings
BelgiumAntwerp5622437223
Gent4618506115
Brussels5127386928
The NetherlandsAmsterdam8934698538
Utrecht8012433619
- -

But what if you cannot make those visual associations? How then can you read a table like the above? Visually impaired people often use a screenreader that reads out information on web pages to them. This is no problem when you're reading plain text but interpreting a table can be quite a challenge for a blind person. Nevertheless, with the proper markup we can replace visual associations by programmatic ones.

- -

This section of the article provides further techniques for making tables as accessible as possible.

- -

Utilizar os cabeçalhos de coluna e linha

- -

Screenreaders will identify all headers and use them to make programmatic associations between those headers and the cells they relate to. The combination of column and row headers will identify and interpret the data in each cell so that screenreader user can interpret the table similarly to how a sighted user does.

- -

We already covered headers in our previous article — see Adding headers with <th> elements.

- -

O atributo de scope

- -

A new topic for this article is the {{htmlattrxref("scope","th")}} attribute, which can be added to the <th> element to tell screenreaders exactly what cells the header is a header for — is it a header for the row it is in, or the column, for example? Looking back to our spending record example from earlier on, you could unambiguously define the column headers as column headers like this:

- -
<thead>
-  <tr>
-    <th scope="col">Purchase</th>
-    <th scope="col">Location</th>
-    <th scope="col">Date</th>
-    <th scope="col">Evaluation</th>
-    <th scope="col">Cost (€)</th>
-  </tr>
-</thead>
- -

And each row could have a header defined like this (if we added row headers as well as column headers):

- -
<tr>
-  <th scope="row">Haircut</th>
-  <td>Hairdresser</td>
-  <td>12/09</td>
-  <td>Great idea</td>
-  <td>30</td>
-</tr>
- -

Screenreaders will recognize markup structured like this, and allow their users to read out the entire column or row at once, for example.

- -

scope has two more possible values — colgroup and rowgroup. these are used for headings that sit over the top of multiple columns or rows. If you look back at the "Items sold..." table at the start of this section of the article, you'll see that the "Clothes" cell sits above the "Trousers", "Skirts", and "Dresses" cells. All of these cells should be marked up as headers (<th>), but "Clothes" is a heading that sits over the top and defines the other three subheadings. "Clothes" therefore should get an attribute of scope="colgroup", whereas the others would get an attribute of scope="col".

- -

A identificação e atributos de cabeçalhos

- -

An alternative to using the scope attribute is to use {{htmlattrxref("id")}} and {{htmlattrxref("headers", "td")}} attributes to create associations between headers and cells. The way they are used is as follows:

- -
    -
  1. You add a unique id to each <th> element.
  2. -
  3. You add a headers attribute to each <td> element. Each headers attribute has to contain a list of the ids of all the <th> elements that act as a header for that cell, separated by spaces.
  4. -
- -

This gives your HTML table an explicit definition of the position of each cell in the table, defined by the header(s) for each column and row it is part of, kind of like a spreadsheet. For it to work well, the table really needs both column and row headers.

- -

Returning to our spending costs example, the previous two snippets could be rewritten like this:

- -
<thead>
-  <tr>
-    <th id="purchase">Purchase</th>
-    <th id="location">Location</th>
-    <th id="date">Date</th>
-    <th id="evaluation">Evaluation</th>
-    <th id="cost">Cost (€)</th>
-  </tr>
-</thead>
-<tbody>
-<tr>
-  <th id="haircut">Haircut</th>
-  <td headers="location haircut">Hairdresser</td>
-  <td headers="date haircut">12/09</td>
-  <td headers="evaluation haircut">Great idea</td>
-  <td headers="cost haircut">30</td>
-</tr>
-
-  ...
-
-</tbody>
- -
-

Nota: This method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for errors.  The scope approach is usually enough for most tables.

-
- -

Aprendizagem ativa: manipular scope e cabeçalhos

- -
    -
  1. For this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a new directory.
  2. -
  3. Now try adding in the appropriate scope attributes to make this table more appropriate.
  4. -
  5. Finally, try making another copy of the starter files, and this time make the table more accessible using id and headers attributes.
  6. -
- -
-

Nota: You can check your work against our finished examples — see items-sold-scope.html (also see this live) and items-sold-headers.html (see this live too).

-
- -

Resumo

- -

There are a few other things you could learn about table HTML, but we have really given all you need to know at this moment in time. At this point, you might want to go and learn about styling HTML tables — see Styling Tables.

- -
{{PreviousMenuNext("Learn/HTML/Tables/Basics", "Learn/HTML/Tables/Structuring_planet_data", "Learn/HTML/Tables")}}
- -
- - - - - -
diff --git a/files/pt-pt/learn/html/tables/basicos/index.html b/files/pt-pt/learn/html/tables/basicos/index.html deleted file mode 100644 index 98908322c9..0000000000 --- a/files/pt-pt/learn/html/tables/basicos/index.html +++ /dev/null @@ -1,650 +0,0 @@ ---- -title: HTML - o essencial de tabela -slug: Learn/HTML/Tables/Basicos -tags: - - Aprender - - Artigo - - HTML - - Linha - - Principiante - - básicos - - cabeçalho - - coluna - - célula - - essencial - - tabelas -translation_of: Learn/HTML/Tables/Basics ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/HTML/Tables/Avancada", "Learn/HTML/Tables")}}
- -

Este artigo inicia-o nas tabelas HTML, abrangendo o essencial, tais como linhas e células, cabeçalhos, distribuir as células por várias colunas e linhas, e como agrupar todas as células em uma coluna para fins de estilização.

- - - - - - - - - - - - -
Pré-requisitos:O essencial de HTML (consulte Introdução ao HTML).
Objetivo:Familiarizar-se com as tabelas HTML.
- -

O que é uma tabela?

- -

Uma tabela é um conjunto estruturado de dados constituído por linhas e colunas (dados tabulares). Uma tabela permite consultar, fácil e rapidamente, valores que indiquem alguma relação entre diferentes tipos de dados, por exemplo, uma pessoa e a sua idade, ou os dias da semana num horário de uma piscina.

- -

A sample table showing names and ages of some people - Chris 38, Dennis 45, Sarah 29, Karen 47.

- -

A swimming timetable showing a sample data table

- -

As tabelas são utilizadas muito frequentemente na sociedade humana, já há muito tempo, como prova este documento dos US Census, datado de 1800:

- -

A very old parchment document; the data is not easily readable, but it clearly shows a data table being used.

- -

Não é, portanto, surpreendente que os criadores do HTML forneceram um meio de estruturar e apresentar dados tabulares na web.

- -

Como é que uma tabela funciona?

- -

O propósito de uma tabela é ser rígida. A informação é interpretada facilmente através de associação visual entre cabeçalhos de linhas e colunas. Olhe para a tabela em baixo, por exemplo, e encontre um gigante gasoso Joviano com 62 luas. Pode chegar à resposta associando os cabeçalhos das linhas e colunas relevantes.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Dados de planetas no sistema solar (Factos planetários retirados de  Nasa's Planetary Fact Sheet - Metric)
 NomeMassa (1024kg)Diâmetro (km)Densidade (kg/m3)Gravidade (m/s2)Duração do dia (horas)Distância do Sol (106km)Temperatura média (°C)Número de luasNotas
Planetas rochososMercúrio0.3304 87954273,74222,657,91670O mais próximo do Sol
Vénus4.8712 10452438,92802,0108,24640 
Terra5.9712 75655149,824,0149,6151O nosso mundo
Marte0.6426 79239333,724,7227,9-652O planeta vermelho
Gigantes JovianosGigantes gasososJúpiter1898142 984132623,19,9778,6-11067O maior planeta
Saturno568120 5366879,010,71433,5-14062 
Gigantes geladoUrano86.851 11812718,717,22872,5-19527 
Neptuno10249 528163811,016,14495,1-20014 
Planetas anõesPlutão0.01462 37020950,7153,35906,4-2255Desclassificado como planeta em 2006, mas tal ainda é controverso.
- -

Quando executada corretamente, até cegos podem interpretar dados tabulares numa tabela de HTML — uma tabela de HTML bem sucedida deve melhorar a experiência utilizadores com deficiências visuais.

- -

Estilização da tabela

- -

Também pode ver este exemplo ao vivo no GitHub! Algo que vai notar é que a tabela parece um pouco mais legível lá — isto acontece porque a tabela em cima tem estilização mínima, ao passo que a versão do GitHub aplica estilos CSS mais significativos.

- -

Não se iluda; para as tabelas serem eficazes na internet, tem que fornecer alguma informação de estilos com CSS, assim como uma boa estrutura sólida com HTML. Neste módulo focamo-nos na parte de HTML; para saber mais sobre a parte de CSS deve visitar o nosso artigo sobre Estilizar tabelas, quando acabar de ler este.

- -

Não nos vamos focar em CSS neste módulo, mas proporcionamos uma folha de estilos CSS mínima que pode usar para tornar as suas tabelas mais legíveis do que se não tivesse estilo. Pode obter a folha de estilos aqui, e também pode obter um modelo HTML que aplica a folha de estilos — juntando estes dois documentos terá um bom ponto de partida para fazer experiências com tabelas HTML.

- -

Quando NÃO deverá utilizar tabelas HTML?

- -

Tabelas em HTML devem ser utilizdas para mostrar dados tabulares — é para isso que foram concebidas. Infelizmente, muitas pessoas costumavam usar tabelas HTML para dispor páginas web: por exemplo, uma linha contém o cabeçalho, uma linha possui o conteúdo, organizado em colunas, outra linha contém o rodapé, etc. Esta prática era comum porque o suporte para CSS nos vários navegadores costumava ser horrível. Hoje em dia, layouts com tabelas são muito menos comuns, mas ainda os poderá encontrar em alguns cantos da internet. Poderá encontrar mais detalhes e um exemplo no artigo Layouts de páginas no nosso Módulo de Acessibilidade.

- -

Resumidamente, recorrer a tabelas para dispor elementos em vez de Técnicas de layout CSS é má ideia. As razões principais são as seguintes:

- -
    -
  1. Layouts com tabelas reduzem acessibilidade de utilizadores com deficiências visuais: Os leitores de ecrãs, usados por cegos, interpretam as etiquetas existentes na página HTML e lêem o conteúdo em voz alta. Como tabelas não são uma ferramenta adequada para o layout, e a marcação é mais complexa do que se recorresse a técnicas de layout de CSS, a informação dada pelos leitores de ecrãs será confusa para os seus utilizadores.
  2. -
  3. Tabelas produzem "sopa" de etiquetas: Como já foi referido, layouts com tabelas geralmente envolvem estruturas de marcação mais complexas do que as técnicas de layout próprias. Isto torna o código mais difícil de escrever, manter e depurar.
  4. -
  5. Tabelas não são automaticamente responsivas: Ao usar contentores próprios (como {{htmlelement("header")}}, {{htmlelement("section")}}, {{htmlelement("article")}}, ou {{htmlelement("div")}}), a sua largura por omissão é 100% do elemento pai. Tabelas, pelo contrário, são dimensionadas de acordo com o seu conteúdo, pelo que são necessárias medidas adicionais para conseguir que o estilo do layout funcione eficazmente numa variedade de dispositivos.
  6. -
- -

Aprendizagem ativa: Criar a sua primeira tabela

- -

We've talked table theory enough, so, let's dive into a practical example and build up a simple table.

- -
    -
  1. First of all, make a local copy of blank-template.html and minimal-table.css in a new directory on your local machine.
  2. -
  3. The content of every table is enclosed by these two tags : <table></table>. Add these inside the body of your HTML.
  4. -
  5. The smallest container inside a table is a table cell, which is created by a <td> element ('td' stands for 'table data'). Add the following inside your table tags: -
    <td>Hi, I'm your first cell.</td>
    -
  6. -
  7. If we want a row of four cells, we need to copy these tags three times. Update the contents of your table to look like so: -
    <td>Hi, I'm your first cell.</td>
    -<td>I'm your second cell.</td>
    -<td>I'm your third cell.</td>
    -<td>I'm your fourth cell.</td>
    -
  8. -
- -

As you will see, the cells are not placed underneath each other, rather they are automatically aligned with other on the same row. Each <td> element creates a single cell and together they make up the first row. Every cell we add makes the row grow longer.

- -

To stop this row from growing and start placing subsequent cells on a second row, we need to use the <tr> element ('tr' stands for 'table row'). Let's investigate this now.

- -
    -
  1. Place the four cells you've already created inside <tr> tags, like so: - -
    <tr>
    -  <td>Hi, I'm your first cell.</td>
    -  <td>I'm your second cell.</td>
    -  <td>I'm your third cell.</td>
    -  <td>I'm your fourth cell.</td>
    -</tr>
    -
  2. -
  3. Now you've made one row, have a go at making one or two more — each row needs to be wrapped in an additional <tr> element, with each cell contained in a <td>.
  4. -
- -

This should result in a table that looks something like the following:

- - - - - - - - - - - - - - - - -
Hi, I'm your first cell.I'm your second cell.I'm your third cell.I'm your fourth cell.
Second row, first cell.Cell 2.Cell 3.Cell 4.
- -
-

Nota:também pode encontrar isto no GitHub, como simple-table.html (veja-a em execução).

-
- -

Adicionar cabeçalhos com elementos <th>

- -

Now let's turn our attention to table headers — special cells that go at the start of a row or column and define the type of data that row or column contains (as an example, see the "Person" and "Age" cells in the first example shown in this article). To illustrate why they are useful, have a look at the following table example. First the source code:

- -
<table>
-  <tr>
-    <td>&nbsp;</td>
-    <td>Knocky</td>
-    <td>Flor</td>
-    <td>Ella</td>
-    <td>Juan</td>
-  </tr>
-  <tr>
-    <td>Breed</td>
-    <td>Jack Russell</td>
-    <td>Poodle</td>
-    <td>Streetdog</td>
-    <td>Cocker Spaniel</td>
-  </tr>
-  <tr>
-    <td>Age</td>
-    <td>16</td>
-    <td>9</td>
-    <td>10</td>
-    <td>5</td>
-  </tr>
-  <tr>
-    <td>Owner</td>
-    <td>Mother-in-law</td>
-    <td>Me</td>
-    <td>Me</td>
-    <td>Sister-in-law</td>
-  </tr>
-  <tr>
-    <td>Eating Habits</td>
-    <td>Eats everyone's leftovers</td>
-    <td>Nibbles at food</td>
-    <td>Hearty eater</td>
-    <td>Will eat till he explodes</td>
-  </tr>
-</table>
- -

Em baixo, tem a tabela renderizada:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 KnockyFlorEllaJuan
BreedJack RussellPoodleStreetdogCocker Spaniel
Age169105
OwnerMother-in-lawMeMeSister-in-law
Eating HabitsEats everyone's leftoversNibbles at foodHearty eaterWill eat till he explodes
- -

The problem here is that, while you can kind of make out what's going on, it is not as easy to cross reference data as it could be. If the column and row headings stood out in some way, it would be much better.

- -

Aprendizagem ativa: cabeçalhos de tabela

- -

Let's have a go at improving this table.

- -
    -
  1. First, make a local copy of our dogs-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same Dogs example as you saw above.
  2. -
  3. To recognize the table headers as headers, both visually and semantically, you can use the <th> element ('th' stand for 'table header'). This works in exactly the same way as a <td>, except that it denotes a header, not a normal cell. Go into your HTML, and change all the <td> elements surrounding the table headers into <th> elements.
  4. -
  5. Save your HTML and load it in a browser, and you should see that the headers now look like headers.
  6. -
- -
-

Nota: You can find our finished example at dogs-table-fixed.html on GitHub (see it live also).

-
- -

Porque é que os cabeçalhos são úteis?

- -

We have already partially answered this question — it is easier to find the data you are looking for when the headers clearly stand out, and the design just generally looks better.

- -
-

Nota: Table headings come with some default styling — they are bold and centered even if you don't add your own styling to the table, to help them stand out.

-
- -

Tables headers also have an added benefit — along with the scope attribute (which we'll learn about in the next article), they allow you to make tables more accessible by associating each header with all the data in the same row or column. Screenreaders are then able to read out a whole row or column of data at once, which is pretty useful.

- -

Permitir que as células sejam distribuídas por múltiplas filas e colunas

- -

Sometimes we want cells to span multiple rows or columns. Take the following simple example, which shows the names of common animals. In some cases, we want to show the names of the males and females next to the animal name. Sometimes we don't, and in such cases we just want the animal name to span the whole table.

- -

The initial markup looks like this:

- -
<table>
-  <tr>
-    <th>Animals</th>
-  </tr>
-  <tr>
-    <th>Hippopotamus</th>
-  </tr>
-  <tr>
-    <th>Horse</th>
-    <td>Mare</td>
-  </tr>
-  <tr>
-    <td>Stallion</td>
-  </tr>
-  <tr>
-    <th>Crocodile</th>
-  </tr>
-  <tr>
-    <th>Chicken</th>
-    <td>Cock</td>
-  </tr>
-  <tr>
-    <td>Rooster</td>
-  </tr>
-</table>
- -

But the output doesn't give us quite what we want:

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Animals
Hippopotamus
HorseMare
Stallion
Crocodile
ChickenCock
Rooster
- -

We need a way to get "Animals", "Hippopotamus", and "Crocodile" to span across two columns, and "Horse" and "Chicken" to span downwards over two rows. Fortunately, table headers and cells have the colspan and rowspan attributes, which allow us to do just those things. Both accept a unitless number value, which equals the number of rows or columns you want spanned. For example, colspan="2" makes a cell span two columns.

- -

Let's use colspan and rowspan to improve this table.

- -
    -
  1. First, make a local copy of our animals-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same animals example as you saw above.
  2. -
  3. Next, use colspan to make "Animals", "Hippopotamus", and "Crocodile" span across two columns.
  4. -
  5. Finally, use rowspan to make "Horse" and "Chicken" span across two rows.
  6. -
  7. Save and open your code in a browser to see the improvement.
  8. -
- -
-

Note: You can find our finished example at animals-table-fixed.html on GitHub (see it live also).

-
- - -
- -

Proporcionar estilização comum para colunas

- -

There is one last feature we'll tell you about in this article before we move on. HTML has a method of defining styling information for an entire column of data all in one place — the <col> and <colgroup> elements. These exist because it can be a bit annoying and inefficient having to specify styling on columns — you generally have to specify your styling information on every <td> or <th> in the column, or use a complex selector such as {{cssxref(":nth-child()")}}.

- -

Take the following simple example:

- -
<table>
-  <tr>
-    <th>Data 1</th>
-    <th style="background-color: yellow">Data 2</th>
-  </tr>
-  <tr>
-    <td>Calcutta</td>
-    <td style="background-color: yellow">Orange</td>
-  </tr>
-  <tr>
-    <td>Robots</td>
-    <td style="background-color: yellow">Jazz</td>
-  </tr>
-</table>
- -

Which gives us the following result:

- - - - - - - - - - - - - - - - -
Data 1Data 2
CalcuttaOrange
RobotsJazz
- -

This isn't ideal, as we have to repeat the styling information across all three cells in the column (we'd probably have a class set on all three in a real project and specify the styling in a separate stylesheet). Instead of doing this, we can specify the information once, on a <col> element. <col> elements are  specified inside a <colgroup> container just below the opening <table> tag. We could create the same effect as we see above by specifying our table as follows:

- -
<table>
-  <colgroup>
-    <col>
-    <col style="background-color: yellow">
-  </colgroup>
-  <tr>
-    <th>Data 1</th>
-    <th>Data 2</th>
-  </tr>
-  <tr>
-    <td>Calcutta</td>
-    <td>Orange</td>
-  </tr>
-  <tr>
-    <td>Robots</td>
-    <td>Jazz</td>
-  </tr>
-</table>
- -

Effectively we are defining two "style columns", one specifying styling information for each column. We are not styling the first column, but we still have to include a blank <col> element — if we didn't, the styling would just be applied to the first column.

- -

If we wanted to apply the styling information to both columns, we could just include one <col> element with a span attribute on it, like this:

- -
<colgroup>
-  <col style="background-color: yellow" span="2">
-</colgroup>
- -

Just like colspan and rowspan, span takes a unitless number value that specifies the number of columns you want the styling to apply to.

- -

Aprendizagem ativa: colgroup e col

- -

Now it's time to have a go yourself.

- -

Below you can see the timetable of a languages teacher. On Friday she has a new class teaching Dutch all day, but she also teaches German for a few periods on Tuesday and Thursdays. She wants to highlight the columns containing the days she is teaching.

- -

{{EmbedGHLiveSample("learning-area/html/tables/basic/timetable-fixed.html", '100%', 320)}}

- -

Recreate the table by following the steps below.

- -
    -
  1. First, make a local copy of our timetable.html file in a new directory on your local machine. The HTML contains the same table you saw above, minus the column styling information.
  2. -
  3. Add a <colgroup> element at the top of the table, just underneath the <table> tag, in which you can add your <col> elements (see the remaining steps below).
  4. -
  5. The first two columns need to be left unstyled.
  6. -
  7. Add a background color to the third column. The value for your style attribute is background-color:#97DB9A;
  8. -
  9. Set a separate width on the fourth column. The value for your style attribute is width: 42px;
  10. -
  11. Add a background color to the fifth column. The value for your style attribute is background-color: #97DB9A;
  12. -
  13. Add a different background color plus a border to the sixth column, to signify that this is a special day and she's teaching a new class. The values for your style attribute are background-color:#DCC48E; border:4px solid #C1437A;
  14. -
  15. The last two days are free days, so just set them to no background color but a set width; the value for the style attribute is width: 42px;
  16. -
- -

See how you get on with the example. If you get stuck, or want to check your work, you can find our version on GitHub as timetable-fixed.html (see it live also).

- -

Resumo

- -

That just about wraps up the basics of HTML Tables. In the next article we will look at some slightly more advanced table features, and start to think how accessible they are for visually impaired people.

- -
{{NextMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
- -
-

Neste módulo

- - -
- -
- - - - - -
diff --git a/files/pt-pt/learn/html/tables/basics/index.html b/files/pt-pt/learn/html/tables/basics/index.html new file mode 100644 index 0000000000..98908322c9 --- /dev/null +++ b/files/pt-pt/learn/html/tables/basics/index.html @@ -0,0 +1,650 @@ +--- +title: HTML - o essencial de tabela +slug: Learn/HTML/Tables/Basicos +tags: + - Aprender + - Artigo + - HTML + - Linha + - Principiante + - básicos + - cabeçalho + - coluna + - célula + - essencial + - tabelas +translation_of: Learn/HTML/Tables/Basics +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/HTML/Tables/Avancada", "Learn/HTML/Tables")}}
+ +

Este artigo inicia-o nas tabelas HTML, abrangendo o essencial, tais como linhas e células, cabeçalhos, distribuir as células por várias colunas e linhas, e como agrupar todas as células em uma coluna para fins de estilização.

+ + + + + + + + + + + + +
Pré-requisitos:O essencial de HTML (consulte Introdução ao HTML).
Objetivo:Familiarizar-se com as tabelas HTML.
+ +

O que é uma tabela?

+ +

Uma tabela é um conjunto estruturado de dados constituído por linhas e colunas (dados tabulares). Uma tabela permite consultar, fácil e rapidamente, valores que indiquem alguma relação entre diferentes tipos de dados, por exemplo, uma pessoa e a sua idade, ou os dias da semana num horário de uma piscina.

+ +

A sample table showing names and ages of some people - Chris 38, Dennis 45, Sarah 29, Karen 47.

+ +

A swimming timetable showing a sample data table

+ +

As tabelas são utilizadas muito frequentemente na sociedade humana, já há muito tempo, como prova este documento dos US Census, datado de 1800:

+ +

A very old parchment document; the data is not easily readable, but it clearly shows a data table being used.

+ +

Não é, portanto, surpreendente que os criadores do HTML forneceram um meio de estruturar e apresentar dados tabulares na web.

+ +

Como é que uma tabela funciona?

+ +

O propósito de uma tabela é ser rígida. A informação é interpretada facilmente através de associação visual entre cabeçalhos de linhas e colunas. Olhe para a tabela em baixo, por exemplo, e encontre um gigante gasoso Joviano com 62 luas. Pode chegar à resposta associando os cabeçalhos das linhas e colunas relevantes.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Dados de planetas no sistema solar (Factos planetários retirados de  Nasa's Planetary Fact Sheet - Metric)
 NomeMassa (1024kg)Diâmetro (km)Densidade (kg/m3)Gravidade (m/s2)Duração do dia (horas)Distância do Sol (106km)Temperatura média (°C)Número de luasNotas
Planetas rochososMercúrio0.3304 87954273,74222,657,91670O mais próximo do Sol
Vénus4.8712 10452438,92802,0108,24640 
Terra5.9712 75655149,824,0149,6151O nosso mundo
Marte0.6426 79239333,724,7227,9-652O planeta vermelho
Gigantes JovianosGigantes gasososJúpiter1898142 984132623,19,9778,6-11067O maior planeta
Saturno568120 5366879,010,71433,5-14062 
Gigantes geladoUrano86.851 11812718,717,22872,5-19527 
Neptuno10249 528163811,016,14495,1-20014 
Planetas anõesPlutão0.01462 37020950,7153,35906,4-2255Desclassificado como planeta em 2006, mas tal ainda é controverso.
+ +

Quando executada corretamente, até cegos podem interpretar dados tabulares numa tabela de HTML — uma tabela de HTML bem sucedida deve melhorar a experiência utilizadores com deficiências visuais.

+ +

Estilização da tabela

+ +

Também pode ver este exemplo ao vivo no GitHub! Algo que vai notar é que a tabela parece um pouco mais legível lá — isto acontece porque a tabela em cima tem estilização mínima, ao passo que a versão do GitHub aplica estilos CSS mais significativos.

+ +

Não se iluda; para as tabelas serem eficazes na internet, tem que fornecer alguma informação de estilos com CSS, assim como uma boa estrutura sólida com HTML. Neste módulo focamo-nos na parte de HTML; para saber mais sobre a parte de CSS deve visitar o nosso artigo sobre Estilizar tabelas, quando acabar de ler este.

+ +

Não nos vamos focar em CSS neste módulo, mas proporcionamos uma folha de estilos CSS mínima que pode usar para tornar as suas tabelas mais legíveis do que se não tivesse estilo. Pode obter a folha de estilos aqui, e também pode obter um modelo HTML que aplica a folha de estilos — juntando estes dois documentos terá um bom ponto de partida para fazer experiências com tabelas HTML.

+ +

Quando NÃO deverá utilizar tabelas HTML?

+ +

Tabelas em HTML devem ser utilizdas para mostrar dados tabulares — é para isso que foram concebidas. Infelizmente, muitas pessoas costumavam usar tabelas HTML para dispor páginas web: por exemplo, uma linha contém o cabeçalho, uma linha possui o conteúdo, organizado em colunas, outra linha contém o rodapé, etc. Esta prática era comum porque o suporte para CSS nos vários navegadores costumava ser horrível. Hoje em dia, layouts com tabelas são muito menos comuns, mas ainda os poderá encontrar em alguns cantos da internet. Poderá encontrar mais detalhes e um exemplo no artigo Layouts de páginas no nosso Módulo de Acessibilidade.

+ +

Resumidamente, recorrer a tabelas para dispor elementos em vez de Técnicas de layout CSS é má ideia. As razões principais são as seguintes:

+ +
    +
  1. Layouts com tabelas reduzem acessibilidade de utilizadores com deficiências visuais: Os leitores de ecrãs, usados por cegos, interpretam as etiquetas existentes na página HTML e lêem o conteúdo em voz alta. Como tabelas não são uma ferramenta adequada para o layout, e a marcação é mais complexa do que se recorresse a técnicas de layout de CSS, a informação dada pelos leitores de ecrãs será confusa para os seus utilizadores.
  2. +
  3. Tabelas produzem "sopa" de etiquetas: Como já foi referido, layouts com tabelas geralmente envolvem estruturas de marcação mais complexas do que as técnicas de layout próprias. Isto torna o código mais difícil de escrever, manter e depurar.
  4. +
  5. Tabelas não são automaticamente responsivas: Ao usar contentores próprios (como {{htmlelement("header")}}, {{htmlelement("section")}}, {{htmlelement("article")}}, ou {{htmlelement("div")}}), a sua largura por omissão é 100% do elemento pai. Tabelas, pelo contrário, são dimensionadas de acordo com o seu conteúdo, pelo que são necessárias medidas adicionais para conseguir que o estilo do layout funcione eficazmente numa variedade de dispositivos.
  6. +
+ +

Aprendizagem ativa: Criar a sua primeira tabela

+ +

We've talked table theory enough, so, let's dive into a practical example and build up a simple table.

+ +
    +
  1. First of all, make a local copy of blank-template.html and minimal-table.css in a new directory on your local machine.
  2. +
  3. The content of every table is enclosed by these two tags : <table></table>. Add these inside the body of your HTML.
  4. +
  5. The smallest container inside a table is a table cell, which is created by a <td> element ('td' stands for 'table data'). Add the following inside your table tags: +
    <td>Hi, I'm your first cell.</td>
    +
  6. +
  7. If we want a row of four cells, we need to copy these tags three times. Update the contents of your table to look like so: +
    <td>Hi, I'm your first cell.</td>
    +<td>I'm your second cell.</td>
    +<td>I'm your third cell.</td>
    +<td>I'm your fourth cell.</td>
    +
  8. +
+ +

As you will see, the cells are not placed underneath each other, rather they are automatically aligned with other on the same row. Each <td> element creates a single cell and together they make up the first row. Every cell we add makes the row grow longer.

+ +

To stop this row from growing and start placing subsequent cells on a second row, we need to use the <tr> element ('tr' stands for 'table row'). Let's investigate this now.

+ +
    +
  1. Place the four cells you've already created inside <tr> tags, like so: + +
    <tr>
    +  <td>Hi, I'm your first cell.</td>
    +  <td>I'm your second cell.</td>
    +  <td>I'm your third cell.</td>
    +  <td>I'm your fourth cell.</td>
    +</tr>
    +
  2. +
  3. Now you've made one row, have a go at making one or two more — each row needs to be wrapped in an additional <tr> element, with each cell contained in a <td>.
  4. +
+ +

This should result in a table that looks something like the following:

+ + + + + + + + + + + + + + + + +
Hi, I'm your first cell.I'm your second cell.I'm your third cell.I'm your fourth cell.
Second row, first cell.Cell 2.Cell 3.Cell 4.
+ +
+

Nota:também pode encontrar isto no GitHub, como simple-table.html (veja-a em execução).

+
+ +

Adicionar cabeçalhos com elementos <th>

+ +

Now let's turn our attention to table headers — special cells that go at the start of a row or column and define the type of data that row or column contains (as an example, see the "Person" and "Age" cells in the first example shown in this article). To illustrate why they are useful, have a look at the following table example. First the source code:

+ +
<table>
+  <tr>
+    <td>&nbsp;</td>
+    <td>Knocky</td>
+    <td>Flor</td>
+    <td>Ella</td>
+    <td>Juan</td>
+  </tr>
+  <tr>
+    <td>Breed</td>
+    <td>Jack Russell</td>
+    <td>Poodle</td>
+    <td>Streetdog</td>
+    <td>Cocker Spaniel</td>
+  </tr>
+  <tr>
+    <td>Age</td>
+    <td>16</td>
+    <td>9</td>
+    <td>10</td>
+    <td>5</td>
+  </tr>
+  <tr>
+    <td>Owner</td>
+    <td>Mother-in-law</td>
+    <td>Me</td>
+    <td>Me</td>
+    <td>Sister-in-law</td>
+  </tr>
+  <tr>
+    <td>Eating Habits</td>
+    <td>Eats everyone's leftovers</td>
+    <td>Nibbles at food</td>
+    <td>Hearty eater</td>
+    <td>Will eat till he explodes</td>
+  </tr>
+</table>
+ +

Em baixo, tem a tabela renderizada:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 KnockyFlorEllaJuan
BreedJack RussellPoodleStreetdogCocker Spaniel
Age169105
OwnerMother-in-lawMeMeSister-in-law
Eating HabitsEats everyone's leftoversNibbles at foodHearty eaterWill eat till he explodes
+ +

The problem here is that, while you can kind of make out what's going on, it is not as easy to cross reference data as it could be. If the column and row headings stood out in some way, it would be much better.

+ +

Aprendizagem ativa: cabeçalhos de tabela

+ +

Let's have a go at improving this table.

+ +
    +
  1. First, make a local copy of our dogs-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same Dogs example as you saw above.
  2. +
  3. To recognize the table headers as headers, both visually and semantically, you can use the <th> element ('th' stand for 'table header'). This works in exactly the same way as a <td>, except that it denotes a header, not a normal cell. Go into your HTML, and change all the <td> elements surrounding the table headers into <th> elements.
  4. +
  5. Save your HTML and load it in a browser, and you should see that the headers now look like headers.
  6. +
+ +
+

Nota: You can find our finished example at dogs-table-fixed.html on GitHub (see it live also).

+
+ +

Porque é que os cabeçalhos são úteis?

+ +

We have already partially answered this question — it is easier to find the data you are looking for when the headers clearly stand out, and the design just generally looks better.

+ +
+

Nota: Table headings come with some default styling — they are bold and centered even if you don't add your own styling to the table, to help them stand out.

+
+ +

Tables headers also have an added benefit — along with the scope attribute (which we'll learn about in the next article), they allow you to make tables more accessible by associating each header with all the data in the same row or column. Screenreaders are then able to read out a whole row or column of data at once, which is pretty useful.

+ +

Permitir que as células sejam distribuídas por múltiplas filas e colunas

+ +

Sometimes we want cells to span multiple rows or columns. Take the following simple example, which shows the names of common animals. In some cases, we want to show the names of the males and females next to the animal name. Sometimes we don't, and in such cases we just want the animal name to span the whole table.

+ +

The initial markup looks like this:

+ +
<table>
+  <tr>
+    <th>Animals</th>
+  </tr>
+  <tr>
+    <th>Hippopotamus</th>
+  </tr>
+  <tr>
+    <th>Horse</th>
+    <td>Mare</td>
+  </tr>
+  <tr>
+    <td>Stallion</td>
+  </tr>
+  <tr>
+    <th>Crocodile</th>
+  </tr>
+  <tr>
+    <th>Chicken</th>
+    <td>Cock</td>
+  </tr>
+  <tr>
+    <td>Rooster</td>
+  </tr>
+</table>
+ +

But the output doesn't give us quite what we want:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Animals
Hippopotamus
HorseMare
Stallion
Crocodile
ChickenCock
Rooster
+ +

We need a way to get "Animals", "Hippopotamus", and "Crocodile" to span across two columns, and "Horse" and "Chicken" to span downwards over two rows. Fortunately, table headers and cells have the colspan and rowspan attributes, which allow us to do just those things. Both accept a unitless number value, which equals the number of rows or columns you want spanned. For example, colspan="2" makes a cell span two columns.

+ +

Let's use colspan and rowspan to improve this table.

+ +
    +
  1. First, make a local copy of our animals-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same animals example as you saw above.
  2. +
  3. Next, use colspan to make "Animals", "Hippopotamus", and "Crocodile" span across two columns.
  4. +
  5. Finally, use rowspan to make "Horse" and "Chicken" span across two rows.
  6. +
  7. Save and open your code in a browser to see the improvement.
  8. +
+ +
+

Note: You can find our finished example at animals-table-fixed.html on GitHub (see it live also).

+
+ + +
+ +

Proporcionar estilização comum para colunas

+ +

There is one last feature we'll tell you about in this article before we move on. HTML has a method of defining styling information for an entire column of data all in one place — the <col> and <colgroup> elements. These exist because it can be a bit annoying and inefficient having to specify styling on columns — you generally have to specify your styling information on every <td> or <th> in the column, or use a complex selector such as {{cssxref(":nth-child()")}}.

+ +

Take the following simple example:

+ +
<table>
+  <tr>
+    <th>Data 1</th>
+    <th style="background-color: yellow">Data 2</th>
+  </tr>
+  <tr>
+    <td>Calcutta</td>
+    <td style="background-color: yellow">Orange</td>
+  </tr>
+  <tr>
+    <td>Robots</td>
+    <td style="background-color: yellow">Jazz</td>
+  </tr>
+</table>
+ +

Which gives us the following result:

+ + + + + + + + + + + + + + + + +
Data 1Data 2
CalcuttaOrange
RobotsJazz
+ +

This isn't ideal, as we have to repeat the styling information across all three cells in the column (we'd probably have a class set on all three in a real project and specify the styling in a separate stylesheet). Instead of doing this, we can specify the information once, on a <col> element. <col> elements are  specified inside a <colgroup> container just below the opening <table> tag. We could create the same effect as we see above by specifying our table as follows:

+ +
<table>
+  <colgroup>
+    <col>
+    <col style="background-color: yellow">
+  </colgroup>
+  <tr>
+    <th>Data 1</th>
+    <th>Data 2</th>
+  </tr>
+  <tr>
+    <td>Calcutta</td>
+    <td>Orange</td>
+  </tr>
+  <tr>
+    <td>Robots</td>
+    <td>Jazz</td>
+  </tr>
+</table>
+ +

Effectively we are defining two "style columns", one specifying styling information for each column. We are not styling the first column, but we still have to include a blank <col> element — if we didn't, the styling would just be applied to the first column.

+ +

If we wanted to apply the styling information to both columns, we could just include one <col> element with a span attribute on it, like this:

+ +
<colgroup>
+  <col style="background-color: yellow" span="2">
+</colgroup>
+ +

Just like colspan and rowspan, span takes a unitless number value that specifies the number of columns you want the styling to apply to.

+ +

Aprendizagem ativa: colgroup e col

+ +

Now it's time to have a go yourself.

+ +

Below you can see the timetable of a languages teacher. On Friday she has a new class teaching Dutch all day, but she also teaches German for a few periods on Tuesday and Thursdays. She wants to highlight the columns containing the days she is teaching.

+ +

{{EmbedGHLiveSample("learning-area/html/tables/basic/timetable-fixed.html", '100%', 320)}}

+ +

Recreate the table by following the steps below.

+ +
    +
  1. First, make a local copy of our timetable.html file in a new directory on your local machine. The HTML contains the same table you saw above, minus the column styling information.
  2. +
  3. Add a <colgroup> element at the top of the table, just underneath the <table> tag, in which you can add your <col> elements (see the remaining steps below).
  4. +
  5. The first two columns need to be left unstyled.
  6. +
  7. Add a background color to the third column. The value for your style attribute is background-color:#97DB9A;
  8. +
  9. Set a separate width on the fourth column. The value for your style attribute is width: 42px;
  10. +
  11. Add a background color to the fifth column. The value for your style attribute is background-color: #97DB9A;
  12. +
  13. Add a different background color plus a border to the sixth column, to signify that this is a special day and she's teaching a new class. The values for your style attribute are background-color:#DCC48E; border:4px solid #C1437A;
  14. +
  15. The last two days are free days, so just set them to no background color but a set width; the value for the style attribute is width: 42px;
  16. +
+ +

See how you get on with the example. If you get stuck, or want to check your work, you can find our version on GitHub as timetable-fixed.html (see it live also).

+ +

Resumo

+ +

That just about wraps up the basics of HTML Tables. In the next article we will look at some slightly more advanced table features, and start to think how accessible they are for visually impaired people.

+ +
{{NextMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
+ +
+

Neste módulo

+ + +
+ +
+ + + + + +
diff --git a/files/pt-pt/learn/html/tables/structuring_planet_data/index.html b/files/pt-pt/learn/html/tables/structuring_planet_data/index.html new file mode 100644 index 0000000000..70fbf3601a --- /dev/null +++ b/files/pt-pt/learn/html/tables/structuring_planet_data/index.html @@ -0,0 +1,151 @@ +--- +title: 'Avaliação: Estruturar os dados dos planetas' +slug: Learn/HTML/Tables/Avaliacao_Estruturar_os_dados_dos_planetas +translation_of: Learn/HTML/Tables/Structuring_planet_data +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
+ +

Na nossa avaliação de tabela, nós forncemos-lhe alguns dados dos planetas no nosso sistema solar, para que possa estruturá-los numa tabela HTML .

+ + + + + + + + + + + + +
Pré-requisitos:Before attempting this assessment you should have already worked through all the articles in this module.
Objetivo:To test comprehension of HTML tables and associated features.
+ +

Ponto inicial

+ +

To get this assessment started, make local copies of blank-template.html, minimal-table.css, and planets-data.txt in a new directory in your local computer.

+ +
+

Note: Alternatively, you could use a site like JSBin or Thimble to do your assessment. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have separate JavaScript/CSS panels, feel free to put them inline <script>/<style> elements inside the HTML page.

+
+ +

Sumário do projeto

+ +

You are working at a school; currently your students are studying the planets of our solar system, and you want to provide them with an easy-to-follow set of data to look up facts and figures about the planets. An HTML data table would be ideal — you need to take the raw data you have available and turn it into a table, following the steps below.

+ +

The finished table should look like this:

+ +

+ +

You can also see the example live here (no looking at the source code — don't cheat!)

+ + + +

Passos para concluir

+ +

The following steps describe what you need to do to complete the table example. All the data you'll need is contained in the planets-data.txt file. If you have trouble visualising the data, look at the live example above, or try drawing a diagram.

+ +
    +
  1. Open your copy of blank-template.html, and start the table off by giving it an outer container, a table header, and a table body. You don't need a table footer for this example.
  2. +
  3. Add the provided caption to your table.
  4. +
  5. Add a row to the table header containing all the column headers.
  6. +
  7. Create all the content rows inside the table body, remembering to make all the row headings into headings semantically.
  8. +
  9. Make sure all the content is inserted into the right cells — in the raw data, each row of planet data is shown next to its associated planet.
  10. +
  11. Add attributes to make the row and column headers unambiguously associated with the rows, columns, or rowgroups that they act as headings for.
  12. +
  13. Add a black border just around the column that contains all the planet name row headers.
  14. +
+ +

Dicas e sugestões

+ + + +

Avaliação

+ +

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the Learning Area Discourse thread, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

+ +

{{PreviousMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}

+ +
+ + + + + +
diff --git a/files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html b/files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html new file mode 100644 index 0000000000..f752fdbf6c --- /dev/null +++ b/files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html @@ -0,0 +1,160 @@ +--- +title: JavaScript +slug: Web/CSS/Como_começar/JavaScript +tags: + - 'CSS:Como_começar' +translation_of: Learn/JavaScript/Client-side_web_APIs/Manipulating_documents +translation_of_original: Web/Guide/CSS/Getting_started/JavaScript +--- +

{{ PreviousNext("CSS:Como começar:Mídia", "CSS:Como começar:XBL bindings") }}

+ +

Esta é a Parte II do tutorial. A Parte II contém alguns exemplos que mostram o escopo do CSS no Mozilla.

+ +

Cada página na Parte II ilustra como o CSS interage com algumas outras tecnologias. Estas páginas não são desenhadas para ensinar como usar estas outras tecnologias. Vá para outros tutorias para aprender isto em detalhes.

+ +

Em vez disso, estas páginas são desenhadas para ilustrar os muitos usos do CSS. Para usar estas páginas, você deve ter um conhecimento em CSS, mas você não precisa qualquer conhecimento em outras tecnologias.

+ +

Informação: JavaScript

+ +

JavaScript é uma linguagem de programação. Quando você usa alguma aplicação Mozilla (por exemplo, seu naverador Mozilla) muito do código que o seu computador roda é escrito em JavaScript.

+ +

JavaScript pode interagir com folhas de estilo, permitindo a você escrever programas que mudem o estilo do documento dinamicamente.

+ +

Existem três maneiras para fazer isto:

+ + + + + + + + + + +
Mais detalhes
Para mais informações sobre JavaScript no Mozilla, veja a página JavaScript neste wiki.
+ +

Ação: Uma demonstração de JavaScript

+ +

Criei um novo documento HTML, doc5.html. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:

+ +
+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
+<HTML>
+
+<HEAD>
+<TITLE>Como Começar Mozilla CSS - Demonstração JavaScript</TITLE>
+<LINK rel="stylesheet" type="text/css" href="style5.css">
+<SCRIPT type="text/javascript" src="script5.js"></SCRIPT>
+</HEAD>
+
+<BODY>
+<H1>JavaScript de amostra</H1>
+
+<DIV id="square"></DIV>
+
+<BUTTON type="button" onclick="doDemo(this);">Clique Aqui</BUTTON>
+
+</BODY>
+</HTML>
+
+
+ +

Crie um novo arquivo CSS, style5.css. Copie e cole o conteúdo daqui:

+ +
+
/*** Demonstração JavaScript ***/
+#square {
+  width: 20em;
+  height: 20em;
+  border: 2px inset gray;
+  margin-bottom: 1em;
+  }
+
+button {
+  padding: .5em 2em;
+  }
+
+
+ +

Crie um novo arquivo de texo, script5.js. Copie e cole o conteúdo daqui:

+ +
+
// Demonstração JavaScript
+function doDemo (button) {
+  var square = document.getElementById("square")
+  square.style.backgroundColor = "#fa4"
+  button.setAttribute("disabled", "true")
+  setTimeout(clearDemo, 2000, button)
+  }
+
+function clearDemo (button) {
+  var square = document.getElementById("square")
+  square.style.backgroundColor = "transparent"
+  button.removeAttribute("disabled")
+  }
+
+
+ +

Abra o documento no seu navegador e pressione o botão.

+ +

Este wiki não suporta o JavaScript nas páginas, então não é possível mostrar a demonstração aqui. Deve se parecer como isto, antes e depois de você pressionar o botão:

+ + + + + + + + +
+ + + + + + +
+

Demonstração JavaScript

+
+
+ + + + + + +
+

Demonstração JavaScript

+
+
+ +

Notas sobre esta demonstração:

+ + + + + + + + + + +
Desafio
Mude o script de modo que o quadrado salte para a direita em 20 em quando sua cor mudar, e salte para trás mais tarde.
+ +

O que vem depois?

+ +

Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

+ +

Nesta demonstração, o documento HTML linka o script mesmo que somente o elemento button use o script. Mozilla extende o CSS para que possa ser ligado ao código JavaScript (e também conteúdo e outras folhas de estilo) para elementos selecionados. A próxima página demonstra isto: XBL bindings

+ +

{{ PreviousNext("CSS:Como começar:Mídia", "CSS:Como começar:XBL bindings") }}

diff --git a/files/pt-pt/learn/javascript/first_steps/index.html b/files/pt-pt/learn/javascript/first_steps/index.html new file mode 100644 index 0000000000..02041b3355 --- /dev/null +++ b/files/pt-pt/learn/javascript/first_steps/index.html @@ -0,0 +1,143 @@ +--- +title: JavaScript - Os Primeiros Passos +slug: Learn/JavaScript/Primeiros_passos +tags: + - Artigo + - Avaliação + - Guía + - JavaScript + - Numeros + - Operadores + - Principiante + - Variáveis + - 'l10n:priority' + - modulo + - strings +translation_of: Learn/JavaScript/First_steps +--- +
{{LearnSidebar}}
+ +

In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key building blocks in detail, such as variables, strings, numbers and arrays.

+ +

Pré-requisitos

+ +

Before starting this module, you don't need any previous JavaScript knowledge, but you should have some familiarity with HTML and CSS. You are advised to work through the following modules before starting on JavaScript:

+ + + +
+

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

+
+ +

Guias

+ +
+
O que é o JavaScript?
+
Welcome to the MDN beginner's JavaScript course! In this first article we will look at JavaScript from a high level, answering questions such as "what is it?", and "what is it doing?", and making sure you are comfortable with JavaScript's purpose.
+
A first splash into JavaScript
+
Now you've learned something about the theory of JavaScript, and what you can do with it, we are going to give you a crash course in the basic features of JavaScript via a completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step.
+
What went wrong? Troubleshooting JavaScript
+
When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some simple tips on how to find and fix errors in JavaScript programs.
+
Storing the information you need — Variables
+
After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article we will get down to the real basics, looking at how to work with most basic building blocks of JavaScript — Variables.
+
Basic math in JavaScript — numbers and operators
+
At this point in the course we discuss maths in JavaScript — how we can combine operators and other features to successfully manipulate numbers to do our bidding.
+
Handling text — strings in JavaScript
+
Next we'll turn our attention to strings — this is what pieces of text are called in programming. In this article we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in string, and joining them together.
+
Useful string methods
+
Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.
+
Arrays
+
In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
+
+ +

Avaliações

+ +

The following assessment will test your understanding of the JavaScript basics covered in the guides above.

+ +
+
Silly story generator
+
In this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!
+
+ +
+ + + + + +
diff --git a/files/pt-pt/learn/javascript/primeiros_passos/index.html b/files/pt-pt/learn/javascript/primeiros_passos/index.html deleted file mode 100644 index 02041b3355..0000000000 --- a/files/pt-pt/learn/javascript/primeiros_passos/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: JavaScript - Os Primeiros Passos -slug: Learn/JavaScript/Primeiros_passos -tags: - - Artigo - - Avaliação - - Guía - - JavaScript - - Numeros - - Operadores - - Principiante - - Variáveis - - 'l10n:priority' - - modulo - - strings -translation_of: Learn/JavaScript/First_steps ---- -
{{LearnSidebar}}
- -

In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key building blocks in detail, such as variables, strings, numbers and arrays.

- -

Pré-requisitos

- -

Before starting this module, you don't need any previous JavaScript knowledge, but you should have some familiarity with HTML and CSS. You are advised to work through the following modules before starting on JavaScript:

- - - -
-

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

-
- -

Guias

- -
-
O que é o JavaScript?
-
Welcome to the MDN beginner's JavaScript course! In this first article we will look at JavaScript from a high level, answering questions such as "what is it?", and "what is it doing?", and making sure you are comfortable with JavaScript's purpose.
-
A first splash into JavaScript
-
Now you've learned something about the theory of JavaScript, and what you can do with it, we are going to give you a crash course in the basic features of JavaScript via a completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step.
-
What went wrong? Troubleshooting JavaScript
-
When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some simple tips on how to find and fix errors in JavaScript programs.
-
Storing the information you need — Variables
-
After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article we will get down to the real basics, looking at how to work with most basic building blocks of JavaScript — Variables.
-
Basic math in JavaScript — numbers and operators
-
At this point in the course we discuss maths in JavaScript — how we can combine operators and other features to successfully manipulate numbers to do our bidding.
-
Handling text — strings in JavaScript
-
Next we'll turn our attention to strings — this is what pieces of text are called in programming. In this article we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in string, and joining them together.
-
Useful string methods
-
Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.
-
Arrays
-
In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
-
- -

Avaliações

- -

The following assessment will test your understanding of the JavaScript basics covered in the guides above.

- -
-
Silly story generator
-
In this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!
-
- -
- - - - - -
diff --git a/files/pt-pt/learn/no-servidor/django/index.html b/files/pt-pt/learn/no-servidor/django/index.html deleted file mode 100644 index 295b1e80b4..0000000000 --- a/files/pt-pt/learn/no-servidor/django/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Framework da Web Django (Python) -slug: Learn/No-servidor/Django -tags: - - Aprender - - CodingScripting - - Introdução - - Principiante - - Programação no lado do servidor - - Python - - django -translation_of: Learn/Server-side/Django ---- -
{{LearnSidebar}}
- -

Django é uma framework da web do lado do servidor extremamente popular e cheia de recursos, escrita em Python. O módulo mostra-lhe porque Django é uma das frameworks mais populares de servidor da web, como configurar um ambiente de desenvolvimento, e como começar a utilizá-lo para criar as suas próprias aplicações da web.

- -

Pré-requisitos

- -

Before starting this module you don't need to have any knowledge of Django. Ideally, you would need to understand what server-side web programming and web frameworks are by reading the topics in our Server-side website programming first steps module.

- -

A general knowledge of programming concepts and Python is recommended, but is not essential to understanding the core concepts.

- -
-

Nota: Python is one of the easiest programming languages for novices to read and understand. That said, if you want to understand this module better, there are numerous free books and tutorials available on the Internet to help you out. (new programmers might want to check out the Python for Non Programmers page on the python.org wiki).

-
- -

Guias

- -
-
Django introduction
-
In this first Django article we answer the question "What is Django?" and give you an overview of what makes this web framework special. We'll outline the main features, including some advanced functionality that we won't have time to cover in detail in this module. We'll also show you some of the main building blocks of a Django application, to give you an idea of what it can do before you set it up and start playing.
-
Setting up a Django development environment
-
Now that you know what Django is for, we'll show you how to setup and test a Django development environment on Windows, Linux (Ubuntu), and Mac OS X — whatever common operating system you are using, this article should give you what you need to be able to start developing Django apps.
-
Django Tutorial: The Local Library website
-
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" — an example website we'll be working through and evolving in subsequent articles.
-
Django Tutorial Part 2: Creating a skeleton website
-
This article shows how you can create a "skeleton" website project as a basis, which you can then go on to populate with site-specific settings, urls, models, views, and templates.
-
Django Tutorial Part 3: Using models
-
This article shows how to define models for the LocalLibrary website — models represent the data structures we want to store our app's data in, and also allow Django to store data in a database for us (and modify it later on). It explains what a model is, how it is declared, and some of the main field types. It also briefly shows a few of the main ways you can access model data.
-
Django Tutorial Part 4: Django admin site
-
Now that we've created models for the LocalLibrary website, we'll use the Django Admin site to add some "real" book data. First we'll show you how to register the models with the admin site, then we'll show you how to login and create some data. At the end we show some ways in which you can further improve the presentation of the admin site.
-
Django Tutorial Part 5: Creating our home page
-
We're now ready to add the code to display our first full page — a home page for the LocalLibrary that shows how many records we have of each model type and provides sidebar navigation links to our other pages. Along the way we'll gain practical experience in writing basic URL maps and views, getting records from the database, and using templates.
-
Django Tutorial Part 6: Generic list and detail views
-
This tutorial extends our LocalLibrary website, adding list and detail pages for books and authors. Here we'll learn about generic class-based views, and show how they can reduce the amount of code you have to write for common use cases. We'll also go into URL handling in greater detail, showing how to perform basic pattern matching.
-
Django Tutorial Part 7: Sessions framework
-
This tutorial extends our LocalLibrary website, adding a session-based visit-counter to the home page. This is a relatively simple example, but it does show how you can use the session framework to provide persistent behaviour for anonymous users in your own sites.
-
Django Tutorial Part 8: User authentication and permissions
-
In this tutorial we'll show you how to allow users to login to your site with their own accounts, and how to control what they can do and see based on whether or not they are logged in and their permissions. As part of this demonstration we'll extend the LocalLibrary website, adding login and logout pages, and user- and staff-specific pages for viewing books that have been borrowed.
-
Django Tutorial Part 9: Working with forms
-
In this tutorial we'll show you how to work with HTML Forms in Django, and in particular the easiest way to write forms to create, update, and delete model instances. As part of this demonstration we'll extend the LocalLibrary website so that librarians can renew books, and create, update, and delete authors using our own forms (rather than using the admin application).
-
Django Tutorial Part 10: Testing a Django web application
-
As websites grow they become harder to test manually — not only is there more to test, but, as the interactions between components become more complex, a small change in one area can require many additional tests to verify its impact on other areas. One way to mitigate these problems is to write automated tests, which can easily and reliably be run every time you make a change. This tutorial shows how to automate unit testing of your website using Django's test framework.
-
Django Tutorial Part 11: Deploying Django to production
-
Now you've created (and tested) an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
-
Django web application security
-
Protecting user data is an essential part of any website design. We previously explained some of the more common security threats in the article Web security — this article provides a practical demonstration of how Django's in-built protections handle such threats.
-
- -

Avaliações

- -

The following assessment will test your understanding of how to create a website using Django, as described in the guides listed above.

- -
-
DIY Django mini blog
-
In this assessment you'll use some of the knowledge you've learned from this module to create your own blog.
-
diff --git a/files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html b/files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html deleted file mode 100644 index 242d0be946..0000000000 --- a/files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html +++ /dev/null @@ -1,406 +0,0 @@ ---- -title: Configurar um meio de desenvolvimento Node -slug: Learn/No-servidor/Express_Nodejs/Configurar_um_meio_de_desenvolvimento_Node -tags: - - Ambiente de desenvolvimento - - Aprender - - CodingScripting - - Express - - Introdução - - Node - - Nodo - - Principiante - - lado do servidor - - nodejs - - npm -translation_of: Learn/Server-side/Express_Nodejs/development_environment ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}
- -

Agora que sabe para que serve o Express, nós iremos mostrar-lhe como configurar e testar um ambiente de desenvolvimento Node/Express no Linux, (Ubuntu), macOS e Windows. Qualquer que seja o sistema operativo comum que esteja a utilizar, este artigo deverá fornecer-lhe o que precisa para começar a desenvolver aplicações Express.

- - - - - - - - - - - - -
Pré-requisitos:Know how to open a terminal / command line. Know how to install software packages on your development computer's operating system.
Objetivo:To set up a development environment for Express (X.XX) on your computer.
- -

Resumo do ambiente de desenvolvimento Express

- -

Node and Express make it very easy to set up your computer in order to start developing web applications. This section provides an overview of what tools are needed, explains some of the simplest methods for installing Node (and Express) on Ubuntu, macOS, and Windows, and shows how you can test your installation.

- -

O que é o ambiente de desenvolvimento Express?

- -

The Express development environment includes an installation of Nodejs, the NPM package manager, and (optionally) the Express Application Generator on your local computer.

- -

Node and the NPM package manager are installed together from prepared binary packages, installers, operating system package managers or from source (as shown in the following sections). Express is then installed by NPM as a dependency of your individual Express web applications (along with other libraries like template engines, database drivers, authentication middleware, middleware to serve static files, etc.)

- -

NPM can also be used to (globally) install the Express Application Generator, a handy tool for creating skeleton Express web apps that follow the MVC pattern. The application generator is optional because you don't need to use this tool to create apps that use Express, or construct Express apps that have the same architectural layout or dependencies. We'll be using it though, because it makes getting started a lot easier, and promotes a modular application structure.

- -
-

Nota: Unlike for some other web frameworks, the development environment does not include a separate development web server. In Node/Express a web application creates and runs its own web server!

-
- -

There are other peripheral tools that are part of a typical development environment, including text editors or IDEs for editing code, and source control management tools like Git for safely managing different versions of your code. We are assuming that you've already got these sorts of tools installed (in particular a text editor).

- -

Quais são os sistemas operativos suportados?

- -

Node can be run on Windows, macOS, many "flavours" of Linux, Docker, etc. (there is a full list on the nodejs Downloads page). Almost any personal computer should have the necessary performance to run Node during development. Express is run in a Node environment, and hence can run on any platform that runs Node.

- -

In this article we provide setup instructions for Windows, macOS, and Ubuntu Linux.

- -

Que versão de Node/Express deverei utilizar?

- -

There are many releases of Node — newer releases contain bug fixes, support for more recent versions of ECMAScript (JavaScript) standards, and improvements to the Node APIs. 

- -

Generally you should use the most recent LTS (long-term supported) release as this will be more stable than the "current" release while still having relatively recent features (and is still being actively maintained). You should use the Current release if you need a feature that is not present in the LTS version.

- -

For Express you should always use the latest version.

- -

E as bases de dados e outras dependências?

- -

Other dependencies, such as database drivers, template engines, authentication engines, etc. are part of the application, and are imported into the application environment using the NPM package manager.  We'll discuss them in later app-specific articles.

- -

Instalação de Node

- -

In order to use Express you will first have to install Nodejs and the Node Package Manager (NPM) on your operating system. The following sections explain the easiest way to install the Long Term Supported (LTS) version of Nodejs on Ubuntu Linux 16.04, macOS, and Windows 10.

- -
-

Dica: The sections below show the easiest way to install Node and NPM on our target OS platforms. If you're using another OS or just want to see some of the other approaches for the current platforms then see Installing Node.js via package manager (nodejs.org).

-
- -

macOS e Windows

- -

Installing Node and NPM on Windows and macOS is straightforward because you can just use the provided installer:

- -
    -
  1. Download the required installer: -
      -
    1. Go to https://nodejs.org/en/
    2. -
    3. Select the button to download the LTS build that is "Recommended for most users".
    4. -
    -
  2. -
  3. Install Node by double-clicking on the downloaded file and following the installation prompts.
  4. -
- -

Ubuntu 16.04

- -

The easiest way to install the most recent LTS version of Node 6.x is to use the package manager to get it from the Ubuntu binary distributions repository. This can be done very simply by running the following two commands on your terminal:

- -
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
-sudo apt-get install -y nodejs
-
- -
-

Aviso: Don't install directly from the normal Ubuntu repositories because they contain very old versions of node.

-
- -
    -
- -

Testar a instalação do seu Nodejs e NPM

- -

The easiest way to test that node is installed is to run the "version" command in your terminal/command prompt and check that a version string is returned:

- -
>node -v
-v8.11.3
- -

The Nodejs package manager NPM should also have been installed, and can be tested in the same way:

- -
>npm -v
-5.8.0
- -

As a slightly more exciting test let's create a very basic "pure node" server that simply prints out "Hello World" in the browser when you visit the correct URL in your browser:

- -
    -
  1. Copy the following text into a file named hellonode.js. This uses pure Node features (nothing from Express) and some ES6 syntax: - -
    //Load HTTP module
    -const http = require("http");
    -const hostname = '127.0.0.1';
    -const port = 3000;
    -
    -//Create HTTP server and listen on port 3000 for requests
    -const server = http.createServer((req, res) => {
    -
    -  //Set the response HTTP header with HTTP status and Content type
    -  res.statusCode = 200;
    -  res.setHeader('Content-Type', 'text/plain');
    -  res.end('Hello World\n');
    -});
    -
    -//listen for request on port 3000, and as a callback function have the port listened on logged
    -server.listen(port, hostname, () => {
    -  console.log(`Server running at http://${hostname}:${port}/`);
    -});
    -
    -
    - -

    The code imports the "http" module and uses it to create a server (createServer()) that listens for HTTP requests on port 3000. The script then prints a message to the console about what browser URL you can use to test the server. The createServer() function takes as an argument a callback function that will be invoked when an HTTP request is received — this simply returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World".

    - -
    -

    Nota:  Don't worry if you don't understand exactly what this code is doing yet! We'll explain our code in greater detail once we start using Express!

    -
    -
  2. -
  3. Start the server by navigating into the same directory as your hellonode.js file in your command prompt, and calling node along with the script name, like so: -
    >node hellonode.js
    -Server running at http://127.0.0.1:3000/
    -
    -
  4. -
  5. Navigate to the URL http://127.0.0.1:3000 . If everything is working, the browser should simply display the string "Hello World".
  6. -
- -

Utilização de NPM

- -

Next to Node itself, NPM is the most important tool for working with Node applications. NPM is used to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production, and may also be used to run tests and tools used in the development process. 

- -
-

Nota: From Node's perspective, Express is just another package that you need to install using NPM and then require in your own code.

-
- -

You can manually use NPM to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named package.json. This file lists all the dependencies for a specific JavaScript "package", including the package's name, version, description, initial file to execute, production dependencies, development dependencies, versions of Node it can work with, etc. The package.json file should contain everything NPM needs to fetch and run your application (if you were writing a reusable library you could use this definition to upload your package to the npm respository and make it available for other users).

- -

Adicionar dependências

- -

The following steps show how you can use NPM to download a package, save it into the project dependencies, and then require it in a Node application.

- -
-

Nota: Here we show the instructions to fetch and install the Express package. Later on we'll show how this package, and others, are already specified for us using the Express Application Generator. This section is provided because it is useful to understand how NPM works and what is being created by the application generator.

-
- -
    -
  1. First create a directory for your new application and navigate into it: -
    mkdir myapp
    -cd myapp
    -
  2. -
  3. Use the npm init command to create a package.json file for your application. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is index.js). For now, just accept the defaults: -
    npm init
    - -

    If you display the package.json file (cat package.json), you will see the defaults that you accepted, ending with the license.

    - -
    {
    -  "name": "myapp",
    -  "version": "1.0.0",
    -  "description": "",
    -  "main": "index.js",
    -  "scripts": {
    -    "test": "echo \"Error: no test specified\" && exit 1"
    -  },
    -  "author": "",
    -  "license": "ISC"
    -}
    -
    -
  4. -
  5. Now install Express in the myapp directory and save it in the dependencies list of your package.json file
  6. -
  7. -
    npm install express --save
    - -

    The dependencies section of your package.json will now appear at the end of the package.json file and will include Express.

    - -
    {
    -  "name": "myapp",
    -  "version": "1.0.0",
    -  "description": "",
    -  "main": "index.js",
    -  "scripts": {
    -    "test": "echo \"Error: no test specified\" && exit 1"
    -  },
    -  "author": "",
    -  "license": "ISC",
    -  "dependencies": {
    -    "express": "^4.16.2"
    -  }
    -}
    -
    -
  8. -
  9. To use the library you call the require() function as shown below. -
    const express = require('express')
    -const app = express();
    -
    -app.get('/', (req, res) => {
    -  res.send('Hello World!')
    -});
    -
    -app.listen(8000, () => {
    -  console.log('Example app listening on port 8000!')
    -});
    -
    - -

    This code shows a minimal "HelloWorld" Express web application. This imports the "express" module and uses it to create a server (app) that listens for HTTP requests on port 8000 and prints a message to the console explaining what browser URL you can use to test the server. The app.get() function only responds to HTTP GET requests with the specified URL path ('/'), in this case by calling a function to send our Hello World! message. 
    -
    - Create a file named index.js in the root of the "myapp" application directory and give it the contents shown above.

    -
  10. -
  11. You can start the server by calling node with the script in your command prompt: -
    >node index.js
    -Example app listening on port 8000
    -
    -
  12. -
  13. Navigate to the URL (http://127.0.0.1:8000/). If everything is working, the browser should simply display the string "Hello World!".
  14. -
- -

Dependências de desenvolvimento

- -

If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). For example, to use the popular JavaScript Linting tool eslint you would call NPM as shown:

- -
npm install eslint --save-dev
- -

The following entry would then be added to your application's package.json:

- -
  "devDependencies": {
-    "eslint": "^4.12.1"
-  }
-
- -
-

Nota: "Linters" are tools that perform static analysis on software in order to recognise and report adherence/non-adherance to some set of coding best practice.

-
- -

Execução de tarefas

- -

In addition to defining and fetching dependencies you can also define named scripts in your package.json files and call NPM to execute them with the run-script command. This approach is commonly used to automate running tests and parts of the development or build toolchain (e.g., running tools to minify JavaScript, shrink images, LINT/analyse your code, etc).

- -
-

Nota: Task runners like Gulp and Grunt can also be used to run tests and other external tools.

-
- -

For example, to define a script to run the eslint development dependency that we specified in the previous section we might add the following script block to our package.json file (assuming that our application source is in a folder /src/js):

- -
"scripts": {
-  ...
-  "lint": "eslint src/js"
-  ...
-}
-
- -

To explain a little further, eslint src/js is a command that we could enter in our terminal/command line to run eslint on JavaScript files contained in the src/js directory inside our app directory. Including the above inside our app's package.json file provides a shortcut for this command — lint.

- -

We would then be able to run eslint using NPM by calling:

- -
npm run-script lint
-# OR (using the alias)
-npm run lint
-
- -

This example may not look any shorter than the original command, but you can include much bigger commands inside your npm scripts, including chains of multiple commands. You could identify a single npm script that runs all your tests at once.

- -

Instalar o Gerador de Aplicação Express

- -

The Express Application Generator tool generates an Express application "skeleton". Install the generator using NPM as shown (the -g flag installs the tool globally so that you can call it from anywhere):

- -
npm install express-generator -g
- -

To create an Express app named "helloworld" with the default settings, navigate to where you want to create it and run the app as shown:

- -
express helloworld
- -
-

Nota: You can also specify the template library to use and a number of other settings. Use the help command to see all the options:

- -
express --help
-
- -

 

-
- -

NPM will create the new Express app in a sub folder of your current location, displaying build progress on the console. On completion, the tool will display the commands you need to enter to install the Node dependencies and start the app.

- -
-

The new app will have a package.json file in its root directory. You can open this to see what dependencies are installed, including Express and the template library Jade:

- -
{
-  "name": "helloworld",
-  "version": "0.0.0",
-  "private": true,
-  "scripts": {
-    "start": "node ./bin/www"
-  },
-  "dependencies": {
-    "body-parser": "~1.18.2",
-    "cookie-parser": "~1.4.3",
-    "debug": "~2.6.9",
-    "express": "~4.15.5",
-    "jade": "~1.11.0",
-    "morgan": "~1.9.0",
-    "serve-favicon": "~2.4.5"
-  }
-}
- -

 

-
- -

Install all the dependencies for the helloworld app using NPM as shown:

- -
cd helloworld
-npm install
-
- -

Then run the app (the commands are slightly different for Windows and Linux/macOS), as shown below:

- -
# Run the helloworld on Windows
-SET DEBUG=helloworld:* & npm start
-
-# Run helloworld on Linux/macOS
-DEBUG=helloworld:* npm start
-
- -

The DEBUG command creates useful logging, resulting in an output like that shown below.

- -
>SET DEBUG=helloworld:* & npm start
-
-> helloworld@0.0.0 start D:\Github\expresstests\helloworld
-> node ./bin/www
-
-  helloworld:server Listening on port 3000 +0ms
- -

Open a browser and navigate to http://127.0.0.1:3000/ to see the default Express welcome page.

- -

Express - Generated App Default Screen

- -

We'll talk more about the generated app when we get to the article on generating a skeleton application.

- - - -

Resumo

- -

You now have a Node development environment up and running on your computer that can be used for creating Express web applications. You've also seen how NPM can be used to import Express into an application, and also how you can create applications using the Express Application Generator tool and then run them.

- -

In the next article we start working through a tutorial to build a complete web application using this environment and associated tools.

- -

Consulte também

- - - -

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}

- -

 

- -

Neste módulop

- - - -

 

diff --git a/files/pt-pt/learn/no-servidor/express_nodejs/index.html b/files/pt-pt/learn/no-servidor/express_nodejs/index.html deleted file mode 100644 index 1c7e7413ec..0000000000 --- a/files/pt-pt/learn/no-servidor/express_nodejs/index.html +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: Framework da Web Express (Node.js/JavaScript) -slug: Learn/No-servidor/Express_Nodejs -tags: - - Aprender - - CodingScripting - - Express - - Express.js - - Introdução - - JavaScript - - Node - - Nodo - - Principiante - - Programação no lado do servidor - - node.js -translation_of: Learn/Server-side/Express_Nodejs ---- -
{{LearnSidebar}}
- -

Express é uma das frameworks mais populares, escrita em JavaScript e hospedada dentro do próprio ambiente de execução node.js. Este módulo explica alguns dos benefícios chave desta framework, como configurar o seu ambiente de desenvolvimento e como realizar tarefas comuns de desenvolvimento da web e tarefas de implementação.

- -

Pré-requisitos

- -

Antes de iniciar este módulo, você precisará entender o que são os programas da web e do lado do servidor, idealmente lendo os tópicos no nosso módulo Os primeiros passos de programação do sites da Web no lado do servidor. Um conhecimento geral de conceitos de programação e JavaScript é altamente recomendado, mas não essencial para compreender os conceitos fundamentais.

- -
-

Nota: This website has many useful resources for learning JavaScript in the context of client-side development: JavaScriptJavaScript Guide, JavaScript BasicsJavaScript (learning). The core JavaScript language and concepts are the same for server-side development on Node.js and this material will be relevant. Node.js offers additional APIs for supporting functionality that is useful in browserless environments, e.g. to create HTTP servers and access the file system, but does not support JavaScript APIs for working with the browser and DOM.

- -

This guide will provide some information about working with Node.js and Express, and there are numerous other excellent resources on the Internet and in books — some of these linked from How do I get started with Node.js (StackOverflow) and What are the best resources for learning Node.js? (Quora).

-
- -

Guias

- -
-
Introdução a Express/Node
-
In this first Express article we answer the questions "What is Node?" and "What is Express?" and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).
-
Configurar um ambiente de desenvolvimento Node (Express)
-
Now that you know what Express is for, we'll show you how to set up and test a Node/Express development environment on Windows, Linux (Ubuntu), and Mac OS X. Whatever common operating system you are using, this article should give you what you need to be able to start developing Express apps.
-
Tutorial de Express: O Website - Biblioteca Local
-
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.
-
Tutorial de Express Parte 2: Criar um esqueleto de um website
-
This article shows how you can create a "skeleton" website project, which you can then go on to populate with site-specific routes, templates/views, and databases.
-
Tutorial de Express Parte 3: Usar uma Base de Dados (com Mongoose)
-
This article briefly introduces databases for Node/Express. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways you can access model data.
-
Tutorial de Express Parte 4: Rotas e controladores
-
In this tutorial we'll set up routes (URL handling code) with "dummy" handler functions for all the resource endpoints that we'll eventually need in the LocalLibrary website. On completion, we'll have a modular structure for our route handling code, that we can extend with real handler functions in the following articles. We'll also have a really good understanding of how to create modular routes using Express.
-
Tutorial de Express Parte 5: Exibir dados da biblioteca
-
We're now ready to add the pages that display the LocalLibrary website books and other data. The pages will include a home page that shows how many records we have of each model type, and list and detail pages for all of our models. Along the way we'll gain practical experience in getting records from the database, and using templates.
-
Tutorial de Express Parte 6: Trabalhar com formulários
-
In this tutorial we'll show you how to work with HTML Forms in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.
-
Tutorial de Express Parte 7: Enviar para produção
-
Now you've created an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
-
- -

Consulte também

- -
-
Installing LocalLibrary on PWS/Cloud Foundry
-
This article provides a practical demonstration of how to install LocalLibrary on the Pivotal Web Services PaaS cloud — this is a full-featured, open source alternative to Heroku, the PaaS cloud service used in Part 7 of the tutorial, listed above. PWS/Cloud Foundry is definitely worth checking out if you are looking for an alternative to Heroku (or another PaaS cloud service), or simply feel like trying something different.
-
- -

Adicionar mais tutoriais

- -
-

That's the end of the tutorial articles (for now). If you would like to extend it, other interesting topics to cover are:

- - - -

And of course it would be excellent to have an assessment task!

-
diff --git a/files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html b/files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html deleted file mode 100644 index c39acc6f1d..0000000000 --- a/files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html +++ /dev/null @@ -1,539 +0,0 @@ ---- -title: Introdução a Express/Node -slug: Learn/No-servidor/Express_Nodejs/Introduction -tags: - - Aprender - - CodingScripting - - Express - - Nodo - - Principiante - - lado do servidor - - nodejs -translation_of: Learn/Server-side/Express_Nodejs/Introduction ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/No-servidor/Express_Nodejs", "Learn/Server-side/Express_Nodejs")}}
- -

In this first Express article we answer the questions "What is Node?" (answer: a library) and "What is Express?", and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).

- - - - - - - - - - - - -
Pré-requisitos:Basic computer literacy. A general understanding of server-side website programming, and in particular the mechanics of client-server interactions in websites.
Objetivo:To gain familiarity with what Express is and how it fits in with Node, what functionality it provides, and the main building blocks of an Express application.
- -

Introdução a Node

- -

Node (or more formally Node.js) is an open-source, cross-platform, runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS). As such, the environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs including HTTP and file system libraries.

- -

From a web server development perspective Node has a number of benefits:

- - - -

You can use Node.js to create a simple web server using the Node HTTP package.

- -

Hello Node.js

- -

The following example creates a web server that listens for any kind of HTTP request on the URL http://127.0.0.1:8000/ — when a request is received, the script will respond with the string: "Hello World". If you have already installed node, you can follow these steps to try out the example:

- -
    -
  1. Open Terminal (on Windows, open the command line utility)
  2. -
  3. Create the folder where you want to save the program, for example, "test-node" and then enter it by entering the following command into your terminal:
  4. -
- -
cd test-node
- -
    -
  1. Using your favorite text editor, create a file called "hello.js" and paste the following code into it:
  2. -
- -
// Load HTTP module
-var http = require("http");
-
-// Create HTTP server and listen on port 8000 for requests
-http.createServer(function(request, response) {
-
-   // Set the response HTTP header with HTTP status and Content type
-   response.writeHead(200, {'Content-Type': 'text/plain'});
-
-   // Send the response body "Hello World"
-   response.end('Hello World\n');
-}).listen(8000);
-
-// Print URL for accessing server
-console.log('Server running at http://127.0.0.1:8000/');
- -
    -
  1. Save the file in the folder you created above.
  2. -
  3. Go back to the terminal and type the following command:
  4. -
- -
node "hello.js"
- -

Finally, navigate to "http://localhost:8000" in your web browser; you should see the text "Hello World" in the upper left of an otherwise empty web page.

- -

Estruturas da Web (Frameworks)

- -

Other common web-development tasks are not directly supported by Node itself. If you want to add specific handling for different HTTP verbs (e.g. GET, POST, DELETE, etc.), separately handle requests at different URL paths ("routes"), serve static files, or use templates to dynamically create the response, then you will need to write the code yourself, or you can avoid reinventing the wheel and use a web framework!

- -

Introdução a Express

- -

Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:

- - - -

While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).

- -
-

Nota: This flexibility is a double edged sword. There are middleware packages to address almost any problem or requirement, but working out the right packages to use can sometimes be a challenge. There is also no "right way" to structure an application, and many examples you might find on the Internet are not optimal, or only show a small part of what you need to do in order to develop a web application.

-
- -

De onde veio o Node e o Express?

- -

Node was initially released, for Linux only, in 2009. The NPM package manager was released in 2010, and native Windows support was added in 2012. The current LTS release is Node v8.11.2 while the latest release is Node 10.1.0. This is a tiny snapshot of a rich history; delve into Wikipedia if you want to know more.

- -

Express was initially released in November 2010 and is currently on version 4.16 of the API. You can check out the changelog for information about changes in the current release, and GitHub for more detailed historical release notes.

- -

Quão populares são o Node e Express?

- -

The popularity of a web framework is important because it is an indicator of whether it will continue to be maintained, and what resources are likely to be available in terms of documentation, add-on libraries, and technical support.

- -

There isn't any readily-available and definitive measurement of the popularity of server-side frameworks (although sites like Hot Frameworks attempt to assess popularity using mechanisms like counting the number of GitHub projects and StackOverflow questions for each platform). A better question is whether Node and Express are "popular enough" to avoid the problems of unpopular platforms. Are they continuing to evolve? Can you get help if you need it? Is there an opportunity for you to get paid work if you learn Express?

- -

Based on the number of high profile companies that use Express, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, Express is a popular framework!

- -

Express é opinativo?

- -

Web frameworks often refer to themselves as "opinionated" or "unopinionated".

- -

Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They often support rapid development in a particular domain (solving problems of a particular type) because the right way to do anything is usually well-understood and well-documented. However they can be less flexible at solving problems outside their main domain, and tend to offer fewer choices for what components and approaches they can use.

- -

Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components together to achieve a goal, or even what components should be used. They make it easier for developers to use the most suitable tools to complete a particular task, albeit at the cost that you need to find those components yourself.
-
- Express is unopinionated. You can insert almost any compatible middleware you like into the request handling chain, in almost any order you like. You can structure the app in one file or multiple files, and using any directory structure. You may sometimes feel that you have too many choices!

- -

Como é que o código de Express se parece?

- -

In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what action is needed based on the URL pattern and possibly associated information contained in POST data or GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.

- -

Express provides methods to specify what function is called for a particular HTTP verb (GET, POST, SET, etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response. You can use Express middleware to add support for cookies, sessions, and users, getting POST/GET parameters, etc. You can use any database mechanism supported by Node (Express does not define any database-related behaviour).

- -

The following sections explain some of the common things you'll see when working with Express and Node code.

- -

Helloworld Express

- -

First lets consider the standard Express Hello World example (we discuss each part of this below, and in the following sections).

- -
-

Dica: If you have Node and Express already installed (or if you install them as shown in the next article), you can save this code in a text file called app.js and run it in a bash command prompt by calling:   

- -

./node ./app.js

-
- -
var express = require('express');
-var app = express();
-
-app.get('/', function(req, res) {
-  res.send('Hello World!');
-});
-
-app.listen(3000, function() {
-  console.log('Example app listening on port 3000!');
-});
-
- -

The first two lines require() (import) the express module and create an Express application. This object, which is traditionally named app, has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering a template engine, and modifying application settings that control how the application behaves (e.g. the environment mode, whether route definitions are case sensitive, etc.)

- -

The middle part of the code (the three lines starting with app.get) shows a route definition. The app.get() method specifies a callback function that will be invoked whenever there is an HTTP GET request with a path ('/') relative to the site root. The callback function takes a request and a response object as arguments, and simply calls send() on the response to return the string "Hello World!"

- -

The final block starts up the server on port '3000' and prints a log comment to the console. With the server running, you could go to localhost:3000 in your browser to see the example response returned.

- -

Importação e criação de módulos

- -

A module is a JavaScript library/file that you can import into other code using Node's require() function. Express itself is a module, as are the middleware and database libraries that we use in our Express applications.

- -

The code below shows how we import a module by name, using the Express framework as an example. First we invoke the require() function, specifying the name of the module as a string ('express'), and calling the returned object to create an Express application. We can then access the properties and functions of the application object.

- -
var express = require('express');
-var app = express();
-
- -

You can also create your own modules that can be imported in the same way.

- -
-

Dica: You will want to create your own modules, because this allows you to organise your code into managable parts — a monolithic single-file application is hard to understand and maintain. Using modules also helps you manage your namespace, because only the variables you explicitly export are imported when you use a module.

-
- -

To make objects available outside of a module you just need to assign them to the exports object. For example, the square.js module below is a file that exports area() and perimeter() methods:

- -
exports.area = function(width) { return width * width; };
-exports.perimeter = function(width) { return 4 * width; };
-
- -

We can import this module using require(), and then call the exported method(s) as shown:

- -
var square = require('./square'); // Here we require() the name of the file without the (optional) .js file extension
-console.log('The area of a square with a width of 4 is ' + square.area(4));
- -
-

Nota: You can also specify an absolute path to the module (or a name, as we did initially).

-
- -

If you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports as shown below (you can also do this to make the root of the exports object a constructor or other function):

- -
module.exports = {
-  area: function(width) {
-    return width * width;
-  },
-
-  perimeter: function(width) {
-    return 4 * width;
-  }
-};
-
- -

For a lot more information about modules see Modules (Node API docs).

- -

Utilizar APIs assíncronas

- -

JavaScript code frequently uses asynchronous rather than synchronous APIs for operations that may take some time to complete. A synchronous API is one in which each operation must complete before the next operation can start. For example, the following log functions are synchronous, and will print the text to the console in order (First, Second).

- -
console.log('First');
-console.log('Second');
-
- -

By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the operation is complete). Once the operation finishes, the API will use some mechanism to perform additional operations. For example, the code below will print out "Second, First" because even though setTimeout() method is called first, and returns immediately, the operation doesn't complete for several seconds.

- -
setTimeout(function() {
-   console.log('First');
-   }, 3000);
-console.log('Second');
-
- -

Using non-blocking asynchronous APIs is even more important on Node than in the browser, because Node is a single threaded event-driven execution environment. "single threaded" means that all requests to the server are run on the same thread (rather than being spawned off into separate processes). This model is extremely efficient in terms of speed and server resources, but it does mean that if any of your functions call synchronous methods that take a long time to complete, they will block not just the current request, but every other request being handled by your web application.

- -

There are a number of ways for an asynchronous API to notify your application that it has completed. The most common way is to register a callback function when you invoke the asynchronous API, that will be called back when the operation completes. This is the approach used above.

- -
-

Dica: Using callbacks can be quite "messy" if you have a sequence of dependent asynchronous operations that must be performed in order, because this results in multiple levels of nested callbacks. This problem is commonly known as "callback hell". This problem can be reduced by good coding practices (see http://callbackhell.com/), using a module like async, or even moving to ES6 features like Promises.

-
- -
-

Nota: A common convention for Node and Express is to use error-first callbacks. In this convention the first value in your callback functions is an error value, while subsequent arguments contain success data. There is a good explanation of why this approach is useful in this blog: The Node.js Way - Understanding Error-First Callbacks (fredkschott.com).

-
- -

Criação de manipuladores de rota

- -

In our Hello World Express example (see above), we defined a (callback) route handler function for HTTP GET requests to the site root ('/').

- -
app.get('/', function(req, res) {
-  res.send('Hello World!');
-});
-
- -

The callback function takes a request and a response object as arguments. In this case the method simply calls send() on the response to return the string "Hello World!" There are a number of other response methods for ending the request/response cycle, for example you could call res.json() to send a JSON response or res.sendFile() to send a file.

- -
-

Dica de JavaScript: You can use any argument names you like in the callback functions; when the callback is invoked the first argument will always be the request and the second will always be the response. It makes sense to name them such that you can identify the object you're working with in the body of the callback.

-
- -

The Express application object also provides methods to define route handlers for all the other HTTP verbs, which are mostly used in exactly the same way: post(), put(), delete(), options(), trace(), copy(), lock(), mkcol(), move(), purge(), propfind(), proppatch(), unlock(), report(), mkactivity(), checkout(), merge(), m-search(), notify(), subscribe(), unsubscribe(), patch(), search(), and connect().

- -

There is a special routing method, app.all(), which will be called in response to any HTTP method. This is used for loading middleware functions at a particular path for all request methods. The following example (from the Express documentation) shows a handler that will be executed for requests to /secret irrespective of the HTTP verb used (provided it is supported by the http module).

- -
app.all('/secret', function(req, res, next) {
-  console.log('Accessing the secret section ...');
-  next(); // pass control to the next handler
-});
- -

Routes allow you to match particular patterns of characters in a URL, and extract some values from the URL and pass them as parameters to the route handler (as attributes of the request object passed as a parameter).

- -

Often it is useful to group route handlers for a particular part of a site together and access them using a common route-prefix (e.g. a site with a Wiki might have all wiki-related routes in one file and have them accessed with a route prefix of /wiki/). In Express this is achieved by using the express.Router object. For example, we can create our wiki route in a module named wiki.js, and then export the Router object, as shown below:

- -
// wiki.js - Wiki route module
-
-var express = require('express');
-var router = express.Router();
-
-// Home page route
-router.get('/', function(req, res) {
-  res.send('Wiki home page');
-});
-
-// About page route
-router.get('/about', function(req, res) {
-  res.send('About this wiki');
-});
-
-module.exports = router;
-
- -
-

Note: Adding routes to the Router object is just like adding routes to the app object (as shown previously).

-
- -

To use the router in our main app file we would then require() the route module (wiki.js), then call use() on the Express application to add the Router to the middleware handling path. The two routes will then be accessible from /wiki/ and /wiki/about/.

- -
var wiki = require('./wiki.js');
-// ...
-app.use('/wiki', wiki);
- -

We'll show you a lot more about working with routes, and in particular about using the Router, later on in the linked section Routes and controllers .

- -

Utilização de middleware

- -

Middleware is used extensively in Express apps, for tasks from serving static files to error handling, to compressing HTTP responses. Whereas route functions end the HTTP request-response cycle by returning some response to the HTTP client, middleware functions typically perform some operation on the request or response and then call the next function in the "stack", which might be more middleware or a route handler. The order in which middleware is called is up to the app developer.

- -
-

Nota: The middleware can perform any operation, execute any code, make changes to the request and response object, and it can also end the request-response cycle. If it does not end the cycle then it must call next() to pass control to the next middleware function (or the request will be left hanging).

-
- -

Most apps will use third-party middleware in order to simplify common web development tasks like working with cookies, sessions, user authentication, accessing request POST and JSON data, logging, etc. You can find a list of middleware packages maintained by the Express team (which also includes other popular 3rd party packages). Other Express packages are available on the NPM package manager.

- -

To use third party middleware you first need to install it into your app using NPM. For example, to install the morgan HTTP request logger middleware, you'd do this:

- -
$ npm install morgan
-
- -

You could then call use() on the Express application object to add the middleware to the stack:

- -
var express = require('express');
-var logger = require('morgan');
-var app = express();
-app.use(logger('dev'));
-...
- -
-

Nota: Middleware and routing functions are called in the order that they are declared. For some middleware the order is important (for example if session middleware depends on cookie middleware, then the cookie handler must be added first). It is almost always the case that middleware is called before setting routes, or your route handlers will not have access to functionality added by your middleware.

-
- -

You can write your own middleware functions, and you are likely to have to do so (if only to create error handling code). The only difference between a middleware function and a route handler callback is that middleware functions have a third argument next, which middleware functions are expected to call if they are not that which completes the request cycle (when the middleware function is called, this contains the next function that must be called).

- -

You can add a middleware function to the processing chain with either app.use() or app.add(), depending on whether you want to apply the middleware to all responses or to responses with a particular HTTP verb (GET, POST, etc). You specify routes the same in both cases, though the route is optional when calling app.use().

- -

The example below shows how you can add the middleware function using both methods, and with/without a route.

- -
var express = require('express');
-var app = express();
-
-// An example middleware function
-var a_middleware_function = function(req, res, next) {
-  // ... perform some operations
-  next(); // Call next() so Express will call the next middleware function in the chain.
-}
-
-// Function added with use() for all routes and verbs
-app.use(a_middleware_function);
-
-// Function added with use() for a specific route
-app.use('/someroute', a_middleware_function);
-
-// A middleware function added for a specific HTTP verb and route
-app.get('/', a_middleware_function);
-
-app.listen(3000);
- -
-

Dica de JavaScript: Above we declare the middleware function separately and then set it as the callback. In our previous route handler function we declared the callback function when it was used. In JavaScript, either approach is valid.

-
- -

The Express documentation has a lot more excellent documentation about using and writing Express middleware.

- -

Servindo ficheiros estásticos

- -

You can use the express.static middleware to serve static files, including your images, CSS and JavaScript (static() is the only middleware function that is actually part of Express). For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named 'public' at the same level as where you call node:

- -
app.use(express.static('public'));
-
- -

Any files in the public directory are served by adding their filename (relative to the base "public" directory) to the base URL. So for example:

- -
http://localhost:3000/images/dog.jpg
-http://localhost:3000/css/style.css
-http://localhost:3000/js/app.js
-http://localhost:3000/about.html
-
- -

You can call static() multiple times to serve multiple directories. If a file cannot be found by one middleware function then it will simply be passed on to the subsequent middleware (the order that middleware is called is based on your declaration order).

- -
app.use(express.static('public'));
-app.use(express.static('media'));
-
- -

You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we specify a mount path so that the files are loaded with the prefix "/media":

- -
app.use('/media', express.static('public'));
-
- -

Now, you can load the files that are in the public directory from the /media path prefix.

- -
http://localhost:3000/media/images/dog.jpg
-http://localhost:3000/media/video/cat.mp4
-http://localhost:3000/media/cry.mp3
-
- -

For more information, see Serving static files in Express.

- -

Erros de manipulação

- -

Errors are handled by one or more special middleware functions that have four arguments, instead of the usual three: (err, req, res, next). For example:

- -
app.use(function(err, req, res, next) {
-  console.error(err.stack);
-  res.status(500).send('Something broke!');
-});
-
- -

These can return any content required, but must be called after all other app.use() and routes calls so that they are the last middleware in the request handling process!

- -

Express comes with a built-in error handler, which takes care of any remaining errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack. If you pass an error to next() and you do not handle it in an error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace.

- -
-

Nota: The stack trace is not included in the production environment. To run it in production mode you need to set the the environment variable NODE_ENV to 'production'.

-
- -
-

Nota: HTTP404 and other "error" status codes are not treated as errors. If you want to handle these, you can add a middleware function to do so. For more information see the FAQ.

-
- -

For more information see Error handling (Express docs).

- -

Utilização de bases de dados

- -

Express apps can use any database mechanism supported by Node (Express itself doesn't define any specific additional behaviour/requirements for database management). There are many options, including PostgreSQL, MySQL, Redis, SQLite, MongoDB, etc.

- -

In order to use these you have to first install the database driver using NPM. For example, to install the driver for the popular NoSQL MongoDB you would use the command:

- -
$ npm install mongodb
-
- -

The database itself can be installed locally or on a cloud server. In your Express code you require the driver, connect to the database, and then perform create, read, update, and delete (CRUD) operations. The example below (from the Express documentation) shows how you can find "mammal" records using MongoDB.

- -
//this works with older versions of  mongodb version ~ 2.2.33
-var MongoClient = require('mongodb').MongoClient;
-
-MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
-  if (err) throw err;
-
-  db.collection('mammals').find().toArray(function (err, result) {
-    if (err) throw err;
-
-    console.log(result);
-  });
-});
-
-
-//for mongodb version 3.0 and up
-let MongoClient = require('mongodb').MongoClient;
-MongoClient.connect('mongodb://localhost:27017/animals', function(err, client){
-   if(err) throw err;
-
-   let db = client.db('animals');
-   db.collection('mammals').find().toArray(function(err, result){
-     if(err) throw err;
-     console.log(result);
-     client.close();
-   });
-}
-
- -

 

- -

 

- -

 

- -

Another popular approach is to access your database indirectly, via an Object Relational Mapper ("ORM"). In this approach you define your data as "objects" or "models" and the ORM maps these through to the underlying database format. This approach has the benefit that as a developer you can continue to think in terms of JavaScript objects rather than database semantics, and that there is an obvious place to perform validation and checking of incoming data. We'll talk more about databases in a later article.

- -

For more information see Database integration (Express docs).

- -

Renderização de dados (visualizações)

- -

Template engines (referred to as "view engines" by Express) allow you to specify the structure of an output document in a template, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of documents. Express has support for a number of template engines, and there is a useful comparison of the more popular engines here: Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More.

- -

In your application settings code you set the template engine to use and the location where Express should look for templates using the 'views' and 'view engines' settings, as shown below (you will also have to install the package containing your template library too!)

- -
var express = require('express');
-var app = express();
-
-// Set directory to contain the templates ('views')
-app.set('views', path.join(__dirname, 'views'));
-
-// Set view engine to use, in this case 'some_template_engine_name'
-app.set('view engine', 'some_template_engine_name');
-
- -

The appearance of the template will depend on what engine you use. Assuming that you have a template file named "index.<template_extension>" that contains placeholders for data variables named 'title' and "message", you would call Response.render() in a route handler function to create and send the HTML response:

- -
app.get('/', function(req, res) {
-  res.render('index', { title: 'About dogs', message: 'Dogs rock!' });
-});
- -

For more information see Using template engines with Express (Express docs).

- -

Estrutura de ficheiro

- -

Express makes no assumptions in terms of structure or what components you use. Routes, views, static files, and other application-specific logic can live in any number of files with any directory structure. While it is perfectly possible to have the whole Express application in one file, typically it makes sense to split your application into files based on function (e.g. account management, blogs, discussion boards) and architectural problem domain (e.g. model, view or controller if you happen to be using an MVC architecture).

- -

In a later topic we'll use the Express Application Generator, which creates a modular app skeleton that we can easily extend for creating web applications.

- - - -

Resumo

- -

Congratulations, you've completed the first step in your Express/Node journey! You should now understand Express and Node's main benefits, and roughly what the main parts of an Express app might look like (routes, middleware, error handling, and template code). You should also understand that with Express being an unopinionated framework, the way you pull these parts together and the libraries that you use are largely up to you!

- -

Of course Express is deliberately a very lightweight web application framework, so much of its benefit and potential comes from third party libraries and features. We'll look at those in more detail in the following articles. In our next article we're going to look at setting up a Node development environment, so that you can start seeing some Express code in action.

- -

Consulte também

- - - -
{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}
- -

Neste módulo

- - diff --git a/files/pt-pt/learn/no-servidor/index.html b/files/pt-pt/learn/no-servidor/index.html deleted file mode 100644 index b8cc8d35f7..0000000000 --- a/files/pt-pt/learn/no-servidor/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Programação do site da Web no lado do servidor -slug: Learn/No-servidor -tags: - - Aprender - - Código - - Iniciante - - Introdução - - Programação no servidor - - Scripting - - Servidor - - Tópico -translation_of: Learn/Server-side ---- -
{{LearnSidebar}}
- -

O tópico Sites da Web Dinâmicos - Programação no lado do servidor é uma série de módulos que mostram como criar sites da web dinâmicos; sites da web que entregam informação personalizada em resposta aos pedidos de HTTP. Os módulos proporcionam uma introdução genérica à programação no lado do servidor, bem como guias especificamente desenvolvidos para principiantes sobre como utilizar as estruturas de Django (Python) e Express (Node.js/JavaScript) para criar aplicações básicas.

- -

A maioria dos maiores sites da web utilizam algum tipo de tecnologia no lado do servidor para exibir dados diferentes, conforme o necessário. Por exemplo, imagine quantos produtos é que estão disponíveis na Amazon e imagine quantos artigos é que foram escritos no Facebook? Exibir todo este conteúdo utilizando páginas estáticas completamente diferentes seria absolutamente ineficiente, assim em vez disso, estes sites exibem modelos estáticos (criados utilizando CSS, HTML e JavaScript), e depois atualizam os dados dinamicamente, exibindo-os dentro dos modelos quando necessário, por exemplo, quando tenta ver um produto diferente na Amazon.

- -

No mundo moderno do desenvolvimento da web, aprender sobre o desenvolvimento no lado do servidor é altamente recomendado.

- -

Caminho de aprendizagem

- -

Começar com programação web no servidor é, de um modo geral, mais fácil que começar com desenvolvimento no lado do cliente, pois páginas web dinâmicas tendem a executar operações muito similares (adquirir dados e guardar na base de dados, verificar as permissões dos usuários, registrar usuários, etc.) , e são construídos utilizando frameworks, os quais tornam estas e outras operações de servidores web fáceis.

- -

Ter conhecimentos básicos de conceitos de programação (ou de uma linguagem de programação específica) é útil, mas não essencial. Da mesma forma, experiência com código do lado do cliente não é absolutamente necessária, mas um conhecimento básico irá ajuda-lo a trabalhar melhor com os desenvolvedores que criam o "front-end" do seu website.

- -

Precisará de compreender "como a web funciona". Recomendamos que comece por ler os seguintes tópicos:

- - - -

Com a compreensão básica destes conceitos, estará pronto para continuar no seu caminho pelos módulos nesta secção.

- -

Módulos

- -

This topic contains the following modules. You should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks . 

- -
-
Primeiros passos na programação web em servidores
-
This module provides server-technology-agnostic information about server-side website programming, including answers to fundamental questions about server-side programming — "what it is", "how it differs from client-side programming", and "why it is so useful" — and an overview of some of the more popular server-side web frameworks and guidance on how to select the most suitable for your site. Lastly we provide an introductory section on web server security.
-
Framework da Web Django (Python)
-
Django is an extremely popular and fully featured server-side web framework, written in Python. The module explains why Django is such a good web server framework, how to set up a development environment and how to perform common tasks with it.
-
Express Web Framework (Node.js/JavaScript)
-
Express is a popular web framework, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.
-
- -

Consulte também

- -
-
Servidor de Node sem uma framework
-
Este artigo fornece um servidor de ficheiros estático simples criado com Node.js puro, para aqueles que não desejam utilizar uma framework.
-
diff --git a/files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html b/files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html deleted file mode 100644 index 85bd786b58..0000000000 --- a/files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Servidor de Node.js sem uma framework -slug: Learn/No-servidor/Servidor_node_sem_framework -tags: - - JavaScript - - Nodo - - Precisa de Conteúdo - - Servidor - - sem estrutura -translation_of: Learn/Server-side/Node_server_without_framework ---- -
{{LearnSidebar}}
- -

 

- -

Este artigo fornece um servidor de ficheiros estático simples com Node.js puro, sem a utilização de uma framework.

- -

NodeJS tem muitas frameworks para ajudá-lo a ter o seu servidor configurado e a funcionar.

- - - -

Estas não irão corresponder a todas as situações. Um programador pode precisar de criar o seu próprio servidor sem outras dependências.

- -

Exemplo

- -

Um servidor de ficheiros estático simples, criado com Node.js:

- -

 

- -
var http = require('http');
-var fs = require('fs');
-var path = require('path');
-
-http.createServer(function (request, response) {
-    console.log('request ', request.url);
-
-    var filePath = '.' + request.url;
-    if (filePath == './') {
-        filePath = './index.html';
-    }
-
-    var extname = String(path.extname(filePath)).toLowerCase();
-    var contentType = 'text/html';
-    var mimeTypes = {
-        '.html': 'text/html',
-        '.js': 'text/javascript',
-        '.css': 'text/css',
-        '.json': 'application/json',
-        '.png': 'image/png',
-        '.jpg': 'image/jpg',
-        '.gif': 'image/gif',
-        '.wav': 'audio/wav',
-        '.mp4': 'video/mp4',
-        '.woff': 'application/font-woff',
-        '.ttf': 'application/font-ttf',
-        '.eot': 'application/vnd.ms-fontobject',
-        '.otf': 'application/font-otf',
-        '.svg': 'application/image/svg+xml'
-    };
-
-    contentType = mimeTypes[extname] || 'application/octet-stream';
-
-    fs.readFile(filePath, function(error, content) {
-        if (error) {
-            if(error.code == 'ENOENT'){
-                fs.readFile('./404.html', function(error, content) {
-                    response.writeHead(200, { 'Content-Type': contentType });
-                    response.end(content, 'utf-8');
-                });
-            }
-            else {
-                response.writeHead(500);
-                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
-                response.end();
-            }
-        }
-        else {
-            response.writeHead(200, { 'Content-Type': contentType });
-            response.end(content, 'utf-8');
-        }
-    });
-
-}).listen(8125);
-console.log('Server running at http://127.0.0.1:8125/');
- -

 

- -

A efetuar

- -

Estenda este artigo, explicando como é que o código acima funciona. Talvez, uma versão estendida que sirva os ficheiros estáticos e lide com pedidos dinâmicos.

diff --git a/files/pt-pt/learn/questoes_comuns/como_funciona_a_internet/index.html b/files/pt-pt/learn/questoes_comuns/como_funciona_a_internet/index.html deleted file mode 100644 index d2ba60f9a3..0000000000 --- a/files/pt-pt/learn/questoes_comuns/como_funciona_a_internet/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Como funciona Internet? -slug: Learn/Questoes_comuns/Como_funciona_a_Internet -tags: - - Mecânica da Web - - Principiante - - Tutorial -translation_of: Learn/Common_questions/How_does_the_Internet_work ---- -
{{LearnSidebar}}
- -
-

This article discusses what the Internet is and how it works.

-
- - - - - - - - - - - - -
Prerequisites:None, but we encourage you to read the Article on setting project goals first
Objective:You will learn the basics of the technical infrastructure of the Web and the difference between Internet and the Web.
- -

Resumo

- -

The Internet is the backbone of the Web, the technical infrastructure that makes the Web possible. At its most basic, the Internet is a large network of computers which communicate all together.

- -

The history of the Internet is somewhat obscure. It began in the 1960s as a US-army-funded research project, then evolved into a public infrastructure in the 1980s with the support of many public universities and private companies. The various technologies that support the Internet have evolved over time, but the way it works hasn't changed that much: Internet is a way to connect computers all together and ensure that, whatever happens, they find a way to stay connected.

- -

Active Learning

- - - -

Deeper dive

- -

A simple network

- -

When two computers need to communicate, you have to link them, either physically (usually with an Ethernet cable) or wirelessly (for example with WiFi or Bluetooth systems). All modern computers can sustain any of those connections.

- -
-

Note: For the rest of this article, we will only talk about physical cables, but wireless networks work the same.

-
- -

Two computers linked together

- -

Such a network is not limited to two computers. You can connect as many computers as you wish. But it gets complicated quickly. If you're trying to connect, say, ten computers, you need 45 cables, with nine plugs per computer!

- -

Ten computers all together

- -

To solve this problem, each computer on a network is connected to a special tiny computer called a router. This router has only one job: like a signaler at a railway station, it makes sure that a message sent from a given computer arrives at the right destination computer. To send a message to computer B, computer A must send the message to the router, which in turn forwards the message to computer B and makes sure the message is not delivered to computer C.

- -

Once we add a router to the system, our network of 10 computers only requires 10 cables: a single plug for each computer and a router with 10 plugs.

- -

Ten computers with a router

- -

A rede das redes

- -

So far so good. But what about connecting hundreds, thousands, billions of computers? Of course a single router can't scale that far, but, if you read carefully, we said that a router is a computer like any other, so what keeps us from connecting two routers together? Nothing, so let's do that.

- -

Two routers linked together

- -

By connecting computers to routers, then routers to routers, we are able to scale infinitely.

- -

Routers linked to routers

- -

Such a network comes very close to what we call the Internet, but we're missing something. We built that network for our own purposes. There are other networks out there: your friends, your neighbors, anyone can have their own network of computers. But it's not really possible to set cables up between your house and the rest of the world, so how can you handle this? Well, there are already cables linked to your house, for example, electric power and telephone. The telephone infrastructure already connects your house with anyone in the world so it is the perfect wire we need. To connect our network to the telephone infrastructure, we need a special piece of equipment called a modem. This modem turns the information from our network into information manageable by the telephone infrastructure and vice versa.

- -

A router linked to a modem

- -

So we are connected to the telephone infrastructure. The next step is to send the messages from our network to the network we want to reach. To do that, we will connect our network to an Internet Service Provider (ISP). An ISP is a company that manages some special routers that are all linked together and can also access other ISPs' routers. So the message from our network is carried through the network of ISP networks to the destination network. The Internet consists of this whole infrastructure of networks.

- -

Full Internet stack

- -

Encontrar computadores

- -

If you want to send a message to a computer, you have to specify which one. Thus any computer linked to a network has a unique address that identifies it, called an "IP address" (where IP stands for Internet Protocol). It's an address made of a series of four numbers separated by dots, for example: 192.168.2.10.

- -

That's perfectly fine for computers, but we human beings have a hard time remembering that sort of address. To make things easier, we can alias an IP address with a human readable name called a domain name. For example (at the time of writing; IP addresses can change) google.com is the domain name used on top of the IP address 173.194.121.32. So using the domain name is the easiest way for us to reach a computer over the Internet.

- -

Show how a domain name can alias an IP address

- -

Internet e a Web

- -

As you might notice, when we browse the Web with a Web browser, we usually use the domain name to reach a website. Does that mean the Internet and the Web are the same thing? It's not that simple. As we saw, the Internet is a technical infrastructure which allows billions of computers to be connected all together. Among those computers, some computers (called Web servers) can send messages intelligible to web browsers. The Internet is an infrastructure, whereas the Web is a service built on top of the infrastructure. It is worth noting there are several other services built on top of the Internet, such as email and {{Glossary("IRC")}}.

- -

Passos seguintes

- - diff --git a/files/pt-pt/learn/questoes_comuns/congiurar_um_servidor_de_testes_local/index.html b/files/pt-pt/learn/questoes_comuns/congiurar_um_servidor_de_testes_local/index.html deleted file mode 100644 index 389407247d..0000000000 --- a/files/pt-pt/learn/questoes_comuns/congiurar_um_servidor_de_testes_local/index.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: Como configurar um servidor local de testes? -slug: Learn/Questoes_comuns/Congiurar_um_servidor_de_testes_local -tags: - - Aprender - - Nodo - - PHP - - Principiante - - Python - - django - - servidores -translation_of: Learn/Common_questions/set_up_a_local_testing_server ---- -
-

Este artigo explica como configurar um servidor de testes local simples  na sua máquina, e como o utilizar.

-
- - - - - - - - - - - - -
Pré-requisitos:pprimeiro, precisa de saber como é que a Internet funciona, e o que é um servidor da Web.
Objetivo:You will learn how to set up a local testing server.
- -

Ficheiros locais vs. ficheiros remotos

- -

Throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double clicking the HTML file, dragging and dropping it into the browser window, or choosing File > Open... and navigating to the HTML file. There are many ways to achieve this.

- -

If the web address path starts with file:// followed by the path to the file on your local hard drive, a local file is being used. In contrast, if you view one of our examples hosted on GitHub (or an example on some other remote server), the web address will start with http:// or https://, to show that the file has been received via HTTP.

- -

O problema com o teste de ficheiros locais

- -

Some examples won't run if you open them as local files. This can be due to a variety of reasons, the most likely being:

- - - -

Executar um servidor um servidor local de HTTP simples

- -

To get around the problem of async requests, we need to test such examples by running them through a local web server. One of the easiest ways to do this for our purposes is to use Python's SimpleHTTPServer module.

- -

To do this:

- -
    -
  1. -

    Install Python. If you are using Linux or Mac OS X, it should be available on your system already. If you are a Windows user, you can get an installer from the Python homepage and follow the instructions to install it:

    - -
      -
    • Go to python.org
    • -
    • Under the Download section, click the link for Python "3.xxx".
    • -
    • At the bottom of the page, choose the Windows x86 executable installer and download it.
    • -
    • When it has downloaded, run it.
    • -
    • On the first installer page, make sure you check the "Add Python 3.xxx to PATH" checkbox.
    • -
    • Click Install, then click Close when the installation has finished.
    • -
    -
  2. -
  3. -

    Open your command prompt (Windows)/terminal (OS X/Linux). To check Python is installed, enter the following command:

    - -
    python -V
    -
  4. -
  5. -

    This should return a version number. If this is OK, navigate to the directory that your example is inside, using the cd command.

    - -
    # include the directory name to enter it, for example
    -cd Desktop
    -# use two dots to jump up one directory level if you need to
    -cd ..
    -
  6. -
  7. -

    Enter the command to start up the server in that directory:

    - -
    # If Python version returned above is 3.X
    -python -m http.server
    -# If Python version returned above is 2.X
    -python -m SimpleHTTPServer
    -
  8. -
  9. -

    By default, this will run the contents of the directory on a local web server, on port 8000. You can go to this server by going to the URL localhost:8000 in your web browser. Here you'll see the contents of the directory listed — click the HTML file you want to run.

    -
  10. -
- -
-

Note: If you already have something running on port 8000, you can choose another port by running the server command followed by an alternative port number, e.g. python -m http.server 7800 (Python 3.x) or python -m SimpleHTTPServer 7800 (Python 2.x). You can then access your content at localhost:7800.

-
- -

Running server-side languages locally

- -

Python's SimpleHTTPServer module is useful, but it doesn't know how to run code written in languages such as PHP or Python. To handle that you'll need something more — exactly what you'll need depends on the server-side language you are trying to run. Here are a few examples:

- - - -
- - - - -
-
-
 
- -
-
G
- -
M
- -
T
-
- -
-
 
- -
 
-
- -
- - - - - - - - - - - - -
-
 
-
-
 
-
-
 
-
-
 
- -
 
-
-
 
-
-
 
-
-
-
- -
 
- -
 
- -
 
- -
A função de fala é limitada a 200 caracteres
- -
-
 
- - - - - - - - -
-
 
-
Opções : Histórico : Comentários : DonateEncerrar
-
-
-
diff --git a/files/pt-pt/learn/questoes_comuns/index.html b/files/pt-pt/learn/questoes_comuns/index.html deleted file mode 100644 index 62deec5d05..0000000000 --- a/files/pt-pt/learn/questoes_comuns/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: Questões Comuns -slug: Learn/Questoes_comuns -translation_of: Learn/Common_questions ---- -
{{LearnSidebar}}
- -

This section of the Learning Area is designed to provide answers to common questions that may come up, which are not necessarily part of the structured core learning pathways (e.g. the HTML or CSS learning articles.) These articles are designed to work on their own.

- -

Como é que a Web funciona

- -

This section covers web mechanics —questions relating to general knowledge of the Web ecosystem and how it works.

- -
-
-

Como é que a Internet funciona?

-
-
The Internet is the backbone of the Web, the technical infrastructure that makes the Web possible. At its most basic, the Internet is a large network of computers which communicate all together. This article discusses how it works, at a basic level.
-
-

Qual é a diferença entre página da Web, site da Web, servidor da Web, e motor de pesquisa?

-
-
In this article we describe various web-related concepts: webpages, websites, web servers, and search engines. These terms are often confused by newcomers to the Web, or are incorrectly used. Let's learn what they each mean!
-
-

O que é um URL?

-
-
With {{Glossary("Hypertext")}} and {{Glossary("HTTP")}}, URL is one of the key concepts of the Web. It is the mechanism used by {{Glossary("Browser","browsers")}} to retrieve any published resource on the web.
-
-

O que é um nome de domínio?

-
-
Domain names are a key part of the Internet infrastructure. They provide a human-readable address for any web server available on the Internet.
-
-

O que é um servidor da Web?

-
-
The term "Web server" can refer to the hardware or software that serves web sites to clients across the Web — or both of them working together. In this article we go over how web servers work, and why they're important.
-
-

O que são hiperligações?

-
-
In this article, we'll go over what hyperlinks are and why they matter.
-
- -

Ferramentas e configuração

- -

Questions related to the tools/software you can use to build websites.

- -
-
-

How much does it cost to do something on the Web?

-
-
When you're launching a website, you may spend nothing or your costs may go through the roof. In this article we discuss how much everything costs and what you get for what you pay (or don't pay).
-
-

What software do I need to build a website?

-
-
In this article we explain which software components you need when you're editing, uploading, or viewing a website.
-
-

What text editors are available?

-
-
In this article we highlight some things to think about when choosing and installing a text editor for web development.
-
-

How do I set up a basic working environment?

-
-
When working on a web project, you'll want to test it locally before you show it to the world. Some types of code require a server to test, and in this article we'll show you how to set one up. We'll also cover how to put a scalable structure in place so that your files stay organized even when your project gets big.
-
-

What are browser developer tools?

-
-
Every browser features a set of devtools for debugging HTML, CSS, and other web code. This article explains how to use the basic functions of your browser's devtools.
-
-

How do you make sure your website works properly?

-
-
So you've published your website online — very good! But are you sure it works properly? This article provides some basic troubleshooting steps.
-
-

How do you set up a local testing server?

-
-
-
-

This article explains how to set up a simple local testing server on your machine, and the basics of how to use it.

-
-
-
-

How do you upload files to a web server?

-
-
This article shows how to publish your site online with FTP tools — one fo the most common ways to get a website online so others can access it from their computers.
-
-

How do I use GitHub Pages?

-
-
This article provides a basic guide to publishing content using GitHub's gh-pages feature.
-
-

How do you host your website on Google App Engine?

-
-
Looking for a place to host your website? Here's a step-by-step guide to hosting your website on Google App Engine.
-
-

What tools are available to debug and improve website performance?

-
-
This set of articles shows you how to use the Developer Tools in Firefox to debug and improve performance of your website, using the tools to check the memory usage, the JavaScript call tree, the amount of DOM nodes being rendered, and more.
-
- -

Desenho e acessibilidade

- -

This section lists questions related to aesthetics, page structure, accessibility techniques, etc.

- -
-
-

How do I start to design my website?

-
-
This article covers the all-important first step of every project: define what you want to accomplish with it.
-
-

What do common web layouts contain?

-
-
When designing pages for your website, it's good to have an idea of the most common layouts. This article runs thorugh some typical web layouts, looking at the parts that make up each one.
-
-

What is accessibility?

-
-
This article introduces the basic concepts behind web accessibility.
-
-

How can we design for all types of users?

-
-
This article provides basic techniques to help you design websites for any kind of user — quick accessibility wins, and other such things.
-
-

What HTML features promote accessibility?

-
-
This article describes specific features of HTML that can be used to make a web page more accessible to people with different disabilities.
-
- -

Questões sobre HTML, CSS e JavaScript

- -

Para soluções comuns para problemas de HTML/CSS/JavaScript, tente os seguintes artigos:

- - diff --git a/files/pt-pt/learn/questoes_comuns/o_que_e_um_nome_de_dominio/index.html b/files/pt-pt/learn/questoes_comuns/o_que_e_um_nome_de_dominio/index.html deleted file mode 100644 index b490ab9789..0000000000 --- a/files/pt-pt/learn/questoes_comuns/o_que_e_um_nome_de_dominio/index.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: O que é um nome de domíno? -slug: Learn/Questoes_comuns/O_que_e_um_nome_de_dominio -tags: - - Infraestrutura - - Introdução - - Nomes de domínio - - Principiante - - Web -translation_of: Learn/Common_questions/What_is_a_domain_name ---- -
-

In this article we discuss domain names: what they are, how they are structured, and how to get one.

-
- - - - - - - - - - - - -
Pré-requisitos:First you need to know how the Internet works and understand what URLs are.
Objetivo:Learn what domain names are, how they work, and why they are important.
- -

Resumo

- -

Domain names are a key part of the Internet infrastructure. They provide a human-readable address for any web server available on the Internet.

- -

Any Internet-connected computer can be reached through a public {{Glossary("IP")}} Address, which consists of 32 bits for IPv4 (they are usually written as four numbers between 0 and 255, separated by dots (e.g., 173.194.121.32) or which consists of 128 bits for IPv6 (they are usually written as eight groups of 4 hexadecimal numbers, separated by colons (e.g., 2027:0da8:8b73:0000:0000:8a2e:0370:1337). Computers can handle those addresses easily, but people have a hard time finding out who's running the server or what service the website offers. IP addresses are hard to remember and might change over time. To solve all those problems we use human-readable addresses called domain names.

- -

Aprendizagem Ativa

- -

There is no active learning available yet. Please, consider contributing.

- -

Deeper dive

- -

Estrutura dos nomes de domínio

- -

A domain name has a simple structure made of several parts (it might be one part only, two, three...), separated by dots and read from right to left:

- -

Anatomy of the MDN domain name

- -

Each of those  parts provides specific information about the whole domain name.

- -
-
{{Glossary("TLD")}} (Top-Level Domain).
-
The TLD provides the most generic information. TLDs tell users the general purpose of the service behind the domain name. The most generic TLDs (.com, .org, .net) don't require web services to meet strict criteria, but some TLDs enforce stricter policies. For example, local TLDs such as .us, .fr, or .sh can require the service to be provided in a given language or hosted in a certain country.
-
Label (or component)
-
The labels are what follow the TLD. A label can be anything, from one letter to a full sentence. The label located right before the TLD can also be referred as a Secondary Level Domain (SLD). A domain name can have many labels (or components), it is not mandatory nor necessary to have 3 labels to form a domain name. For instance, www.inf.ed.ac.uk is a correct domain name. When controlling the "upper" part of a domain name (e.g. mozilla.org), one can create other domain names (sometimes called "subdomains") (e.g. developer.mozilla.org).
-
- -

Comprar um nome de domínio

- -

Who owns a domain name?

- -

You cannot “buy a domain name”. You pay for the right to use a domain name for one or more years. You can renew your right, and your renewal has priority over other people's applications. But you never own the domain name.

- -

Companies called registrars use domain name registries to keep track of technical and administrative information connecting you to your domain name.

- -
-

Nota : For some domain name, it might not be a registrar which is in charge of keeping track. For instance, every domain name under .fire is managed by Amazon.

-
- -

Encontrar um nome de domínio disponível

- -

To find out whether a given domain name is available,

- - - -
$ whois mozilla.org
-Domain Name:MOZILLA.ORG
-Domain ID: D1409563-LROR
-Creation Date: 1998-01-24T05:00:00Z
-Updated Date: 2013-12-08T01:16:57Z
-Registry Expiry Date: 2015-01-23T05:00:00Z
-Sponsoring Registrar:MarkMonitor Inc. (R37-LROR)
-Sponsoring Registrar IANA ID: 292
-WHOIS Server:
-Referral URL:
-Domain Status: clientDeleteProhibited
-Domain Status: clientTransferProhibited
-Domain Status: clientUpdateProhibited
-Registrant ID:mmr-33684
-Registrant Name:DNS Admin
-Registrant Organization:Mozilla Foundation
-Registrant Street: 650 Castro St Ste 300
-Registrant City:Mountain View
-Registrant State/Province:CA
-Registrant Postal Code:94041
-Registrant Country:US
-Registrant Phone:+1.6509030800
-
- -

As you can see, I can't register mozilla.org because the Mozilla Foundation has already registered it.

- -

On the other hand, let's see if I could register afunkydomainname.org:

- -
$ whois afunkydomainname.org
-NOT FOUND
-
- -

As you can see, the domain does not exist in the whois database (at the time of writing), so we could ask to register it. Good to know!

- -

Obter um nome de domínio

- -

The process is quite straightforward:

- -
    -
  1. Go to a registrar's website.
  2. -
  3. Usually there is a prominent “Get a domain name” call to action. Click on it.
  4. -
  5. Fill out the form with all required details. Make sure especially that you have not misspelled your desired domain name. Once it's paid for, it's too late!
  6. -
  7. The registrar will let you know when the domain name is properly registered. Within a few hours, all DNS servers will have received your DNS information.
  8. -
- -
-

Nota: In this process the registrar asks you for your real-world address. Make sure you fill it properly, since in some countries registrars may be forced to close the domain if they cannot provide a valid address.

-
- -

Atualizar DNS

- -

DNS databases are stored on every DNS server worldwide, and all these servers refer to a few ones called “authoritative name server” or “top-level DNS servers.” Whenever your registrar creates or updates any information for a given domain, the information must be refreshed in every DNS database. Each DNS server that knows about a given domain stores the information for some time before it is automatically invalidated and then refreshed (the DNS server queries an authoritative server again). Thus, it takes some time for DNS servers that know about this domain name to get the up-to-date information.

- -
-

Nota : This time is often called propagation time. However this term is not precise since the update is not propagating itself (top → down). DNS servers queried by your computer (down) are the ones that fetch the information from the authoritative server (top) when they need it.

-
- -

Como funciona um pedido de DNS?

- -

As we already saw, when you want to display a webpage in your browser it's easier to type a domain name than an IP address. Let's take a look at the process:

- -
    -
  1. Type mozilla.org in your browser's location bar.
  2. -
  3. Your browser asks your computer if it already recognizes the IP address identified by this domain name (using a local DNS cache). If it does, the name is translated to the IP address and the browser negotiates contents with the web server. End of story.
  4. -
  5. If your computer does not know which IP is behind the mozilla.org name, it goes on to ask a DNS server, whose job is precisely to tell your computer which IP address matches each registered domain name.
  6. -
  7. Now that the computer knows the requested IP address, your browser can negotiate contents with the web server.
  8. -
- -

Explanation of the steps needed to obtain the result to a DNS request

- -

Passos seguintes

- -

Okay, we talked a lot about processes and architecture. Time to move on.

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/questoes_comuns/o_que_e_um_servidor_da_web/index.html b/files/pt-pt/learn/questoes_comuns/o_que_e_um_servidor_da_web/index.html deleted file mode 100644 index a91ef08d6c..0000000000 --- a/files/pt-pt/learn/questoes_comuns/o_que_e_um_servidor_da_web/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: O que é um servidor da Web? -slug: Learn/Questoes_comuns/O_que_e_um_servidor_da_Web -tags: - - Infraestrutura - - Principiante -translation_of: Learn/Common_questions/What_is_a_web_server ---- -
-

Neste artigo, nós examinamos quais são os servidores da Web, como é que estes funcionam, e por que é que eles são importantes.

-
- - - - - - - - - - - - -
Pré-requisitos:You should already know how the Internet works, and understand the difference between a web page, a web site, a web server and a search engine.
Objetivo:You will learn what a web server is and gain a general understanding of how it works.
- -

Resumo

- -

"Web server" can refer to hardware or software, or both of them working together.

- -
    -
  1. On the hardware side, a web server is a computer that stores a website's component files (e.g. HTML documents, images, CSS stylesheets, and JavaScript files) and delivers them to the end-user's device. It is connected to the Internet and can be accessed through a domain name like mozilla.org.
  2. -
  3. On the software side, a web server includes several parts that control how web users access hosted files, at minimum an HTTP server. An HTTP server is a piece of software that understands {{Glossary("URL","URLs")}} (web addresses) and {{Glossary("HTTP")}} (the protocol your browser uses to view webpages).
  4. -
- -

At the most basic level, whenever a browser needs a file hosted on a web server, the browser requests the file via HTTP. When the request reaches the correct web server (hardware), the HTTP server (software) sends the requested document back, also through HTTP.

- -

Basic representation of a client/server connection through HTTP

- -

To publish a website, you need either a static or a dynamic web server.

- -

A static web server, or stack, consists of a computer (hardware) with an HTTP server (software). We call it "static" because the server sends its hosted files "as-is" to your browser.

- -

A dynamic web server consists of a static web server plus extra software, most commonly an application server and a database. We call it "dynamic" because the application server updates the hosted files before sending them to your browser via the HTTP server.

- -

For example, to produce the final webpages you see in the browser, the application server might fill an HTML template with contents from a database. Sites like MDN or Wikipedia have many thousands of webpages, but they aren't real HTML documents, only a few HTML templates and a giant database. This setup makes it easier and quicker to maintain and deliver the content.

- -

Aprendizagem ativa

- -

Ainda não está disponível nenhuma aprendizagem ativa. Por favor, considere contribuir.

- -

Deeper dive

- -

To fetch a webpage, as we already said, your browser sends a request to the web server, which proceeds to search for the requested file in its own storage space. On finding the file, the server reads it, processes it as needed, and sends it to the browser. Let's look at those steps in more detail.

- -

Hosting files

- -

A web server first has to store the website's files, namely all HTML documents and their related assets, including images, CSS stylesheets, JavaScript files, fonts, and videos.

- -

Technically, you could host all those files on your own computer, but it's far more convenient to store them all on a dedicated web server that

- - - -

For all these reasons, finding a good hosting provider is a key part of building your website. Dig through the various services companies offer and choose one that fits your needs and your budget (services range from free to thousands of dollars per month). You can find more details in this article.

- -

Once you set up a web hosting solution, you just have to upload your files to your web server.

- -

Communicating through HTTP

- -

Second, a web server provides support for {{Glossary("HTTP")}} (Hypertext Transfer Protocol). As its name implies, HTTP specifies how to transfer hypertext (i.e., linked web documents) between two computers.

- -

A protocol is a set of rules for communication between two computers. HTTP is a textual, stateless protocol.

- -
-
Textual
-
All commands are plain-text and human-readable.
-
Stateless
-
Neither the server nor the client remember previous communications. For example, relying on HTTP alone, a server cannot remember a password you typed or what step you're on in a transaction. You need an application server for tasks like that. (We'll cover that sort of technology in further articles.)
-
- -

HTTP provides clear rules for how a client and server communicate. We'll cover HTTP itself in a technical article later on. For now, just be aware of these things:

- - - -

The MDN 404 page as an example of such error pageOn a web server, the HTTP server is responsible for processing and answering incoming requests.

- -
    -
  1. On receiving a request, an HTTP server first checks whether the requested URL matches an existing file.
  2. -
  3. If so, the web server sends the file content back to the browser. If not, an application server builds the necessary file.
  4. -
  5. If neither process is possible, the web server returns an error message to the browser, most commonly "404 Not Found". (That error is so common that many web designers spend quite some time designing 404 error pages.)
  6. -
- -

Static vs. dynamic content

- -

Roughly speaking, a server can serve either static or dynamic content. "Static" means "served as-is". Static websites are the easiest to set up, so we suggest you make your first site a static site.

- -

"Dynamic" means that the server processes the content or even generates it on the fly from a database. This solution provides more flexibility, but the technical stack becomes more difficult to handle, making it dramatically more complex to build the website.

- -

Take for example the page you're reading right now. On the web server hosting it, there is an application server that takes article content from a database, formats it, puts it inside some HTML templates, and sends you the results. In this case, the application server is called Kuma and is built with Python (using the Django framework). The Mozilla team built Kuma for the specific needs of MDN, but there are many similar applications built on many other technologies.

- -

There are so many application servers that it's pretty hard to suggest a particular one. Some application servers cater to specific website categories like blogs, wikis or e-shops; others, called {{Glossary("CMS", "CMSs")}} (content management systems), are more generic. If you're building a dynamic website, take the time to choose a tool that fits your needs. Unless you want to learn some web server programming (which is an exciting area in itself!), you don't need to create your own application server. That's just reinventing the wheel.

- -

Passos seguintes

- -

Now that you are familiar with web servers, you could:

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/questoes_comuns/o_que_e_um_url/index.html b/files/pt-pt/learn/questoes_comuns/o_que_e_um_url/index.html deleted file mode 100644 index b61a73433e..0000000000 --- a/files/pt-pt/learn/questoes_comuns/o_que_e_um_url/index.html +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: O que é um URL? -slug: Learn/Questoes_comuns/O_que_e_um_URL -tags: - - Infraestrutura - - Principiante - - URL -translation_of: Learn/Common_questions/What_is_a_URL ---- -
-

This article discusses Uniform Resource Locators (URLs), explaining what they are and how they're structured.

-
- - - - - - - - - - - - -
Prerequisites:You need to first know how the Internet works, what a Web server is and the concepts behind links on the web.
Objective:You will learn what a URL is and how it works on the Web.
- -

Resumo

- -

With {{Glossary("Hypertext")}} and {{Glossary("HTTP")}}, URL is one of the key concepts of the Web. It is the mechanism used by {{Glossary("Browser","browsers")}} to retrieve any published resource on the web.

- -

URL stands for Uniform Resource Locator. A URL is nothing more than the address of a given unique resource on the Web. In theory, each valid URL points to a unique resource. Such resources can be an HTML page, a CSS document, an image, etc. In practice, there are some exceptions, the most common being a URL pointing to a resource that no longer exists or that has moved. As the resource represented by the URL and the URL itself are handled by the Web server, it is up to the owner of the web server to carefully manage that resource and its associated URL.

- -

Aprendizagem Ativa

- -

There is no active learning available yet. Please, consider contributing.

- -

Deeper dive

- -

Basics: anatomy of a URL

- -

Here are some examples of URLs:

- -
https://developer.mozilla.org
-https://developer.mozilla.org/en-US/docs/Learn/
-https://developer.mozilla.org/en-US/search?q=URL
- -

Any of those URLs can be typed into your browser's address bar to tell it to load the associated page (resource).

- -

A URL is composed of different parts, some mandatory and others optional. Let's see the most important parts using the following URL:

- -
http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument
- -
-
Protocol
-
http:// is the protocol. It indicates which protocol the browser must use. Usually it is the HTTP protocol or its secured version, HTTPS. The Web requires one of these two, but browsers also know how to handle other protocols such as mailto: (to open a mail client) or ftp: to handle file transfer, so don't be surprised if you see such protocols.
-
Domaine Name
-
www.example.com is the domain name. It indicates which Web server is being requested. Alternatively, it is possible to directly use an {{Glossary("IP address")}}, but because it is less convenient, it is not often used on the Web.
-
Port
-
:80 is the port. It indicates the technical "gate" used to access the resources on the web server. It is usually omitted if the web server uses the standard ports of the HTTP protocol (80 for HTTP and 443 for HTTPS) to grant access to its resources. Otherwise it is mandatory.
-
Path to the file
-
/path/to/myfile.html is the path to the resource on the Web server. In the early days of the Web, a path like this represented a physical file location on the Web server. Nowadays, it is mostly an abstraction handled by Web servers without any physical reality.
-
Parameters
-
?key1=value1&key2=value2 are extra parameters provided to the Web server. Those parameters are a list of key/value pairs separated with the & symbol. The Web server can use those parameters to do extra stuff before returning the resource. Each Web server has its own rules regarding parameters, and the only reliable way to know if a specific Web server is handling parameters is by asking the Web server owner.
-
Anchor
-
#SomewhereInTheDocument is an anchor to another part of the resource itself. An anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content located at that "bookmarked" spot. On an HTML document, for example, the browser will scroll to the point where the anchor is defined; on a video or audio document, the browser will try to go to the time the anchor represents. It is worth noting that the part after the #, also known as the fragment identifier, is never sent to the server with the request.
-
- -

{{Note('There are some extra parts and some extra rules regarding URLs, but they are not relevant for regular users or Web developers. Don\'t worry about this, you don\'t need to know them to build and use fully functional URLs.')}}

- -

You might think of a URL like a regular postal mail address: the protocol represents the postal service you want to use, the domain name is the city or town,  and the port is like the zip code; the path represents the building where your mail should be delivered; the parameters represent extra information such as the number of the apartment in the building; and, finally, the anchor represents the actual person to whom you've addressed your mail.

- -

Como utilizar os URLs

- -

Any URL can be typed right inside the browser's address bar to get to the resource behind it. But this is only the tip of the iceberg!

- -

The {{Glossary("HTML")}} language — which will be discussed later on — makes extensive use of URLs:

- - - -

Other technologies, such as {{Glossary("CSS")}} or {{Glossary("JavaScript")}}, use URLs extensively, and these are really the heart of the Web.

- -

URLs absolutos vs URLs relativos

- -

What we saw above is called an absolute URL, but there is also something called a relative URL. Let's examine what that distinction means in more detail.

- -

The required parts of a URL depend to a great extent on the context in which the URL is used. In your browser's address bar, a URL doesn't have any context, so you must provide a full (or absolute) URL, like the ones we saw above. You don't need to include the protocol (the browser uses HTTP by default) or the port (which is only required when the targeted Web server is using some unusual port), but all the other parts of the URL are necessary.

- -

When a URL is used within a document, such as in an HTML page,  things are a bit different. Because the browser already has the document's own URL, it can use this information to fill in the missing parts of any URL available inside that document. We can differentiate between an absolute URL and a relative URL by looking only at the path part of the URL. If the path part of the URL starts with the "/" character, the browser will fetch that resource from the top root of the server, without reference to the context given by the current document.

- -

Let's look at some examples to make this clearer.

- -

Exemplos de URLs absolutos

- -
-
Full URL (the same as the one we used before)
-
-
https://developer.mozilla.org/en-US/docs/Learn
-
-
Implicit protocol
-
-
//developer.mozilla.org/en-US/docs/Learn
- -

In this case, the browser will call that URL with the same protocol as the the one used to load the document hosting that URL.

-
-
Implicit domain name
-
-
/en-US/docs/Learn
- -

This is the most common use case for an absolute URL within an HTML document. The browser will use the same protocol and the same domain name as the one used to load the document hosting that URL. Note: it isn't possible to omit the domain name without omitting the protocol as well.

-
-
- -

Exemplos de URLs relativos

- -

To better understand the following examples, let's assume that the URLs are called from within the document located at the following URL: https://developer.mozilla.org/en-US/docs/Learn

- -
-
Sub-resources
-
-
Skills/Infrastructure/Understanding_URLs
-
- Because that URL does not start with /, the browser will attempt to find the document in a sub-directory of the one containing the current resource. So in this example,  we really want to reach this URL: https://developer.mozilla.org/en-US/docs/Learn/Skills/Infrastructure/Understanding_URLs
-
Going back in the directory tree
-
-
../CSS/display
- -

In this case, we use the ../ writing convention — inherited from the UNIX file system world — to tell the browser we want to go up from one directory. Here we want to reach this URL: https://developer.mozilla.org/en-US/docs/Learn/../CSS/display, which can be simplified to: https://developer.mozilla.org/en-US/docs/CSS/display

-
-
- -

URLs semânticos

- -

Despite their very technical flavor, URLs represent a human-readable entry point for a Web site. They can be memorized, and anyone can enter them into a browser's address bar. People are at the core of the Web, and so it is considered best practice to build what is called semantic URLs.  Semantic URLs  use words with inherent meaning that can be understood by anyone, regardless of their technical know-how.

- -

Linguistic semantics are of course irrelevant to computers. You've probably often seen URLs that look like mashups of random characters. But there are many advantages  to creating human-readable URLs:

- - - -

Passos seguintes

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/questoes_comuns/qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa/index.html b/files/pt-pt/learn/questoes_comuns/qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa/index.html deleted file mode 100644 index 97655e6edf..0000000000 --- a/files/pt-pt/learn/questoes_comuns/qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: >- - Qual é a diferença entre página da Web, site da Web, servidor da Web e - mecanismo de pesquisa? -slug: >- - Learn/Questoes_comuns/Qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa -tags: - - Mecânica da Web - - Principiante -translation_of: Learn/Common_questions/Pages_sites_servers_and_search_engines ---- -
-

In this article, we describe various web-related concepts: web pages, websites, web servers, and search engines. These terms are often confused by newcomers to the web or are incorrectly used. Let's learn what they each mean!

-
- - - - - - - - - - - - -
Prerequisites:You should know how the Internet works.
Objective:Be able to describe the differences between a web page, a website, a web server, and a search engine.
- -

Resumo

- -

As with any area of knowledge, the web comes with a lot of jargon. Don't worry, we won't overwhelm you with all of it (we have a glossary if you're curious). However, there are a few basic terms you need to understand at the outset, since you'll hear these expressions all the time as you read on. It's easy to confuse these terms sometimes since they refer to related but different functionalities. In fact, you'll sometimes see these terms misused in news reports and elsewhere, so getting them mixed up is understandable!

- -

We'll cover these terms and technologies in more detail as we explore further, but these quick definitions will be a great start for you:

- -
-
web page
-
A document which can be displayed in a web browser such as Firefox, Google Chrome, Opera, Microsoft Internet Explorer or Edge, or Apple's Safari. These are also often called just "pages."
-
website
-
A collection of web pages which are grouped together and usually connected together in various ways. Often called a "web site" or simply a "site."
-
web server
-
A computer that hosts a website on the Internet.
-
search engine
-
A web service that helps you find other web pages, such as Google, Bing, Yahoo, or DuckDuckGo. Search engines are normally accessed through a web browser (e.g. you can perform search engine searches directly in the address bar of Firefox, Chrome, etc.) or through a web page (e.g. bing.com or duckduckgo.com).
-
- -

Let's look at a simple analogy — a public library. This is what you would generally do when visiting a library:

- -
    -
  1. Find a search index and look for the title of the book you want.
  2. -
  3. Make a note of the catalog number of the book.
  4. -
  5. Go to the particular section containing the book, find the right catalog number, and get the book.
  6. -
- -

Let's compare the library with a web server:

- - - -

Active learning

- -

There is no active learning available yet. Please, consider contributing.

- -

Deeper dive

- -

So, let's dig deeper into how those four terms are related and why they are sometimes confused with each other.

- -

Página da Web

- -

A web page is a simple document displayable by a {{Glossary("browser")}}. Such documents are written in the {{Glossary("HTML")}} language (which we look into in more detail in other articles). A web page can embed a variety of different types of resources such as:

- - - -
-

Note: Browsers can also display other documents such as {{Glossary("PDF")}} files or images, but the term web page specifically refers to HTML documents. Otherwise, we only use the term document.

-
- -

All web pages available on the web are reachable through a unique address. To access a page, just type its address in your browser address bar:

- -

Example of a web page address in the browser address bar

- -

Sites da Web

- -

A website is a collection of linked web pages (plus their associated resources) that share a unique domain name. Each web page of a given website provides explicit links—most of the time in the form of clickable portion of text—that allow the user to move from one page of the website to another.

- -

To access a website, type its domain name in your browser address bar, and the browser will display the website's main web page, or homepage (casually referred as "the home"):

- -

Example of a web site domain name in the browser address bar

- -

The ideas of a web page and a website are especially easy to confuse for a website that contains only one web page. Such a website is sometimes called a single-page website.

- -

Servidor da Web

- -

A web server is a computer hosting one or more websites. "Hosting" means that all the web pages and their supporting files are available on that computer. The web server will send any web page from the website it is hosting to any user's browser, per user request.

- -

Don't confuse websites and web servers. For example, if you hear someone say, "My website is not responding", it actually means that the web server is not responding and therefore the website is not available. More importantly, since a web server can host multiple websites, the term web server is never used to designate a website, as it could cause great confusion. In our previous example, if we said, "My web server is not responding", it means that multiple websites on that web server are not available.

- -

Mecanismo de Pesquisa

- -

Search engines are a common source of confusion on the web. A search engine is a special kind of website that helps users find web pages from other websites.

- -

There are plenty out there: Google, Bing, Yandex, DuckDuckGo, and many more. Some are generic, some are specialized about certain topics. Use whichever you prefer.

- -

Many beginners on the web confuse search engines and browsers. Let's make it clear: A browser is a piece of software that retrieves and displays web pages; a search engine is a website that helps people find web pages from other websites. The confusion arises because, the first time someone launches a browser, the browser displays a search engine's homepage. This makes sense, because, obviously, the first thing you want to do with a browser is to find a web page to display. Don't confuse the infrastructure (e.g., the browser) with the service (e.g., the search engine). The distinction will help you quite a bit, but even some professionals speak loosely, so don't feel anxious about it.

- -

Here is an instance of Firefox showing a Google search box as its default startup page:

- -

Example of Firefox nightly displaying a custom Google page as default

- -

Passos Seguintes

- - diff --git a/files/pt-pt/learn/server-side/django/index.html b/files/pt-pt/learn/server-side/django/index.html new file mode 100644 index 0000000000..295b1e80b4 --- /dev/null +++ b/files/pt-pt/learn/server-side/django/index.html @@ -0,0 +1,68 @@ +--- +title: Framework da Web Django (Python) +slug: Learn/No-servidor/Django +tags: + - Aprender + - CodingScripting + - Introdução + - Principiante + - Programação no lado do servidor + - Python + - django +translation_of: Learn/Server-side/Django +--- +
{{LearnSidebar}}
+ +

Django é uma framework da web do lado do servidor extremamente popular e cheia de recursos, escrita em Python. O módulo mostra-lhe porque Django é uma das frameworks mais populares de servidor da web, como configurar um ambiente de desenvolvimento, e como começar a utilizá-lo para criar as suas próprias aplicações da web.

+ +

Pré-requisitos

+ +

Before starting this module you don't need to have any knowledge of Django. Ideally, you would need to understand what server-side web programming and web frameworks are by reading the topics in our Server-side website programming first steps module.

+ +

A general knowledge of programming concepts and Python is recommended, but is not essential to understanding the core concepts.

+ +
+

Nota: Python is one of the easiest programming languages for novices to read and understand. That said, if you want to understand this module better, there are numerous free books and tutorials available on the Internet to help you out. (new programmers might want to check out the Python for Non Programmers page on the python.org wiki).

+
+ +

Guias

+ +
+
Django introduction
+
In this first Django article we answer the question "What is Django?" and give you an overview of what makes this web framework special. We'll outline the main features, including some advanced functionality that we won't have time to cover in detail in this module. We'll also show you some of the main building blocks of a Django application, to give you an idea of what it can do before you set it up and start playing.
+
Setting up a Django development environment
+
Now that you know what Django is for, we'll show you how to setup and test a Django development environment on Windows, Linux (Ubuntu), and Mac OS X — whatever common operating system you are using, this article should give you what you need to be able to start developing Django apps.
+
Django Tutorial: The Local Library website
+
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" — an example website we'll be working through and evolving in subsequent articles.
+
Django Tutorial Part 2: Creating a skeleton website
+
This article shows how you can create a "skeleton" website project as a basis, which you can then go on to populate with site-specific settings, urls, models, views, and templates.
+
Django Tutorial Part 3: Using models
+
This article shows how to define models for the LocalLibrary website — models represent the data structures we want to store our app's data in, and also allow Django to store data in a database for us (and modify it later on). It explains what a model is, how it is declared, and some of the main field types. It also briefly shows a few of the main ways you can access model data.
+
Django Tutorial Part 4: Django admin site
+
Now that we've created models for the LocalLibrary website, we'll use the Django Admin site to add some "real" book data. First we'll show you how to register the models with the admin site, then we'll show you how to login and create some data. At the end we show some ways in which you can further improve the presentation of the admin site.
+
Django Tutorial Part 5: Creating our home page
+
We're now ready to add the code to display our first full page — a home page for the LocalLibrary that shows how many records we have of each model type and provides sidebar navigation links to our other pages. Along the way we'll gain practical experience in writing basic URL maps and views, getting records from the database, and using templates.
+
Django Tutorial Part 6: Generic list and detail views
+
This tutorial extends our LocalLibrary website, adding list and detail pages for books and authors. Here we'll learn about generic class-based views, and show how they can reduce the amount of code you have to write for common use cases. We'll also go into URL handling in greater detail, showing how to perform basic pattern matching.
+
Django Tutorial Part 7: Sessions framework
+
This tutorial extends our LocalLibrary website, adding a session-based visit-counter to the home page. This is a relatively simple example, but it does show how you can use the session framework to provide persistent behaviour for anonymous users in your own sites.
+
Django Tutorial Part 8: User authentication and permissions
+
In this tutorial we'll show you how to allow users to login to your site with their own accounts, and how to control what they can do and see based on whether or not they are logged in and their permissions. As part of this demonstration we'll extend the LocalLibrary website, adding login and logout pages, and user- and staff-specific pages for viewing books that have been borrowed.
+
Django Tutorial Part 9: Working with forms
+
In this tutorial we'll show you how to work with HTML Forms in Django, and in particular the easiest way to write forms to create, update, and delete model instances. As part of this demonstration we'll extend the LocalLibrary website so that librarians can renew books, and create, update, and delete authors using our own forms (rather than using the admin application).
+
Django Tutorial Part 10: Testing a Django web application
+
As websites grow they become harder to test manually — not only is there more to test, but, as the interactions between components become more complex, a small change in one area can require many additional tests to verify its impact on other areas. One way to mitigate these problems is to write automated tests, which can easily and reliably be run every time you make a change. This tutorial shows how to automate unit testing of your website using Django's test framework.
+
Django Tutorial Part 11: Deploying Django to production
+
Now you've created (and tested) an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
+
Django web application security
+
Protecting user data is an essential part of any website design. We previously explained some of the more common security threats in the article Web security — this article provides a practical demonstration of how Django's in-built protections handle such threats.
+
+ +

Avaliações

+ +

The following assessment will test your understanding of how to create a website using Django, as described in the guides listed above.

+ +
+
DIY Django mini blog
+
In this assessment you'll use some of the knowledge you've learned from this module to create your own blog.
+
diff --git a/files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html b/files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html new file mode 100644 index 0000000000..242d0be946 --- /dev/null +++ b/files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html @@ -0,0 +1,406 @@ +--- +title: Configurar um meio de desenvolvimento Node +slug: Learn/No-servidor/Express_Nodejs/Configurar_um_meio_de_desenvolvimento_Node +tags: + - Ambiente de desenvolvimento + - Aprender + - CodingScripting + - Express + - Introdução + - Node + - Nodo + - Principiante + - lado do servidor + - nodejs + - npm +translation_of: Learn/Server-side/Express_Nodejs/development_environment +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}
+ +

Agora que sabe para que serve o Express, nós iremos mostrar-lhe como configurar e testar um ambiente de desenvolvimento Node/Express no Linux, (Ubuntu), macOS e Windows. Qualquer que seja o sistema operativo comum que esteja a utilizar, este artigo deverá fornecer-lhe o que precisa para começar a desenvolver aplicações Express.

+ + + + + + + + + + + + +
Pré-requisitos:Know how to open a terminal / command line. Know how to install software packages on your development computer's operating system.
Objetivo:To set up a development environment for Express (X.XX) on your computer.
+ +

Resumo do ambiente de desenvolvimento Express

+ +

Node and Express make it very easy to set up your computer in order to start developing web applications. This section provides an overview of what tools are needed, explains some of the simplest methods for installing Node (and Express) on Ubuntu, macOS, and Windows, and shows how you can test your installation.

+ +

O que é o ambiente de desenvolvimento Express?

+ +

The Express development environment includes an installation of Nodejs, the NPM package manager, and (optionally) the Express Application Generator on your local computer.

+ +

Node and the NPM package manager are installed together from prepared binary packages, installers, operating system package managers or from source (as shown in the following sections). Express is then installed by NPM as a dependency of your individual Express web applications (along with other libraries like template engines, database drivers, authentication middleware, middleware to serve static files, etc.)

+ +

NPM can also be used to (globally) install the Express Application Generator, a handy tool for creating skeleton Express web apps that follow the MVC pattern. The application generator is optional because you don't need to use this tool to create apps that use Express, or construct Express apps that have the same architectural layout or dependencies. We'll be using it though, because it makes getting started a lot easier, and promotes a modular application structure.

+ +
+

Nota: Unlike for some other web frameworks, the development environment does not include a separate development web server. In Node/Express a web application creates and runs its own web server!

+
+ +

There are other peripheral tools that are part of a typical development environment, including text editors or IDEs for editing code, and source control management tools like Git for safely managing different versions of your code. We are assuming that you've already got these sorts of tools installed (in particular a text editor).

+ +

Quais são os sistemas operativos suportados?

+ +

Node can be run on Windows, macOS, many "flavours" of Linux, Docker, etc. (there is a full list on the nodejs Downloads page). Almost any personal computer should have the necessary performance to run Node during development. Express is run in a Node environment, and hence can run on any platform that runs Node.

+ +

In this article we provide setup instructions for Windows, macOS, and Ubuntu Linux.

+ +

Que versão de Node/Express deverei utilizar?

+ +

There are many releases of Node — newer releases contain bug fixes, support for more recent versions of ECMAScript (JavaScript) standards, and improvements to the Node APIs. 

+ +

Generally you should use the most recent LTS (long-term supported) release as this will be more stable than the "current" release while still having relatively recent features (and is still being actively maintained). You should use the Current release if you need a feature that is not present in the LTS version.

+ +

For Express you should always use the latest version.

+ +

E as bases de dados e outras dependências?

+ +

Other dependencies, such as database drivers, template engines, authentication engines, etc. are part of the application, and are imported into the application environment using the NPM package manager.  We'll discuss them in later app-specific articles.

+ +

Instalação de Node

+ +

In order to use Express you will first have to install Nodejs and the Node Package Manager (NPM) on your operating system. The following sections explain the easiest way to install the Long Term Supported (LTS) version of Nodejs on Ubuntu Linux 16.04, macOS, and Windows 10.

+ +
+

Dica: The sections below show the easiest way to install Node and NPM on our target OS platforms. If you're using another OS or just want to see some of the other approaches for the current platforms then see Installing Node.js via package manager (nodejs.org).

+
+ +

macOS e Windows

+ +

Installing Node and NPM on Windows and macOS is straightforward because you can just use the provided installer:

+ +
    +
  1. Download the required installer: +
      +
    1. Go to https://nodejs.org/en/
    2. +
    3. Select the button to download the LTS build that is "Recommended for most users".
    4. +
    +
  2. +
  3. Install Node by double-clicking on the downloaded file and following the installation prompts.
  4. +
+ +

Ubuntu 16.04

+ +

The easiest way to install the most recent LTS version of Node 6.x is to use the package manager to get it from the Ubuntu binary distributions repository. This can be done very simply by running the following two commands on your terminal:

+ +
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
+sudo apt-get install -y nodejs
+
+ +
+

Aviso: Don't install directly from the normal Ubuntu repositories because they contain very old versions of node.

+
+ +
    +
+ +

Testar a instalação do seu Nodejs e NPM

+ +

The easiest way to test that node is installed is to run the "version" command in your terminal/command prompt and check that a version string is returned:

+ +
>node -v
+v8.11.3
+ +

The Nodejs package manager NPM should also have been installed, and can be tested in the same way:

+ +
>npm -v
+5.8.0
+ +

As a slightly more exciting test let's create a very basic "pure node" server that simply prints out "Hello World" in the browser when you visit the correct URL in your browser:

+ +
    +
  1. Copy the following text into a file named hellonode.js. This uses pure Node features (nothing from Express) and some ES6 syntax: + +
    //Load HTTP module
    +const http = require("http");
    +const hostname = '127.0.0.1';
    +const port = 3000;
    +
    +//Create HTTP server and listen on port 3000 for requests
    +const server = http.createServer((req, res) => {
    +
    +  //Set the response HTTP header with HTTP status and Content type
    +  res.statusCode = 200;
    +  res.setHeader('Content-Type', 'text/plain');
    +  res.end('Hello World\n');
    +});
    +
    +//listen for request on port 3000, and as a callback function have the port listened on logged
    +server.listen(port, hostname, () => {
    +  console.log(`Server running at http://${hostname}:${port}/`);
    +});
    +
    +
    + +

    The code imports the "http" module and uses it to create a server (createServer()) that listens for HTTP requests on port 3000. The script then prints a message to the console about what browser URL you can use to test the server. The createServer() function takes as an argument a callback function that will be invoked when an HTTP request is received — this simply returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World".

    + +
    +

    Nota:  Don't worry if you don't understand exactly what this code is doing yet! We'll explain our code in greater detail once we start using Express!

    +
    +
  2. +
  3. Start the server by navigating into the same directory as your hellonode.js file in your command prompt, and calling node along with the script name, like so: +
    >node hellonode.js
    +Server running at http://127.0.0.1:3000/
    +
    +
  4. +
  5. Navigate to the URL http://127.0.0.1:3000 . If everything is working, the browser should simply display the string "Hello World".
  6. +
+ +

Utilização de NPM

+ +

Next to Node itself, NPM is the most important tool for working with Node applications. NPM is used to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production, and may also be used to run tests and tools used in the development process. 

+ +
+

Nota: From Node's perspective, Express is just another package that you need to install using NPM and then require in your own code.

+
+ +

You can manually use NPM to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named package.json. This file lists all the dependencies for a specific JavaScript "package", including the package's name, version, description, initial file to execute, production dependencies, development dependencies, versions of Node it can work with, etc. The package.json file should contain everything NPM needs to fetch and run your application (if you were writing a reusable library you could use this definition to upload your package to the npm respository and make it available for other users).

+ +

Adicionar dependências

+ +

The following steps show how you can use NPM to download a package, save it into the project dependencies, and then require it in a Node application.

+ +
+

Nota: Here we show the instructions to fetch and install the Express package. Later on we'll show how this package, and others, are already specified for us using the Express Application Generator. This section is provided because it is useful to understand how NPM works and what is being created by the application generator.

+
+ +
    +
  1. First create a directory for your new application and navigate into it: +
    mkdir myapp
    +cd myapp
    +
  2. +
  3. Use the npm init command to create a package.json file for your application. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is index.js). For now, just accept the defaults: +
    npm init
    + +

    If you display the package.json file (cat package.json), you will see the defaults that you accepted, ending with the license.

    + +
    {
    +  "name": "myapp",
    +  "version": "1.0.0",
    +  "description": "",
    +  "main": "index.js",
    +  "scripts": {
    +    "test": "echo \"Error: no test specified\" && exit 1"
    +  },
    +  "author": "",
    +  "license": "ISC"
    +}
    +
    +
  4. +
  5. Now install Express in the myapp directory and save it in the dependencies list of your package.json file
  6. +
  7. +
    npm install express --save
    + +

    The dependencies section of your package.json will now appear at the end of the package.json file and will include Express.

    + +
    {
    +  "name": "myapp",
    +  "version": "1.0.0",
    +  "description": "",
    +  "main": "index.js",
    +  "scripts": {
    +    "test": "echo \"Error: no test specified\" && exit 1"
    +  },
    +  "author": "",
    +  "license": "ISC",
    +  "dependencies": {
    +    "express": "^4.16.2"
    +  }
    +}
    +
    +
  8. +
  9. To use the library you call the require() function as shown below. +
    const express = require('express')
    +const app = express();
    +
    +app.get('/', (req, res) => {
    +  res.send('Hello World!')
    +});
    +
    +app.listen(8000, () => {
    +  console.log('Example app listening on port 8000!')
    +});
    +
    + +

    This code shows a minimal "HelloWorld" Express web application. This imports the "express" module and uses it to create a server (app) that listens for HTTP requests on port 8000 and prints a message to the console explaining what browser URL you can use to test the server. The app.get() function only responds to HTTP GET requests with the specified URL path ('/'), in this case by calling a function to send our Hello World! message. 
    +
    + Create a file named index.js in the root of the "myapp" application directory and give it the contents shown above.

    +
  10. +
  11. You can start the server by calling node with the script in your command prompt: +
    >node index.js
    +Example app listening on port 8000
    +
    +
  12. +
  13. Navigate to the URL (http://127.0.0.1:8000/). If everything is working, the browser should simply display the string "Hello World!".
  14. +
+ +

Dependências de desenvolvimento

+ +

If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). For example, to use the popular JavaScript Linting tool eslint you would call NPM as shown:

+ +
npm install eslint --save-dev
+ +

The following entry would then be added to your application's package.json:

+ +
  "devDependencies": {
+    "eslint": "^4.12.1"
+  }
+
+ +
+

Nota: "Linters" are tools that perform static analysis on software in order to recognise and report adherence/non-adherance to some set of coding best practice.

+
+ +

Execução de tarefas

+ +

In addition to defining and fetching dependencies you can also define named scripts in your package.json files and call NPM to execute them with the run-script command. This approach is commonly used to automate running tests and parts of the development or build toolchain (e.g., running tools to minify JavaScript, shrink images, LINT/analyse your code, etc).

+ +
+

Nota: Task runners like Gulp and Grunt can also be used to run tests and other external tools.

+
+ +

For example, to define a script to run the eslint development dependency that we specified in the previous section we might add the following script block to our package.json file (assuming that our application source is in a folder /src/js):

+ +
"scripts": {
+  ...
+  "lint": "eslint src/js"
+  ...
+}
+
+ +

To explain a little further, eslint src/js is a command that we could enter in our terminal/command line to run eslint on JavaScript files contained in the src/js directory inside our app directory. Including the above inside our app's package.json file provides a shortcut for this command — lint.

+ +

We would then be able to run eslint using NPM by calling:

+ +
npm run-script lint
+# OR (using the alias)
+npm run lint
+
+ +

This example may not look any shorter than the original command, but you can include much bigger commands inside your npm scripts, including chains of multiple commands. You could identify a single npm script that runs all your tests at once.

+ +

Instalar o Gerador de Aplicação Express

+ +

The Express Application Generator tool generates an Express application "skeleton". Install the generator using NPM as shown (the -g flag installs the tool globally so that you can call it from anywhere):

+ +
npm install express-generator -g
+ +

To create an Express app named "helloworld" with the default settings, navigate to where you want to create it and run the app as shown:

+ +
express helloworld
+ +
+

Nota: You can also specify the template library to use and a number of other settings. Use the help command to see all the options:

+ +
express --help
+
+ +

 

+
+ +

NPM will create the new Express app in a sub folder of your current location, displaying build progress on the console. On completion, the tool will display the commands you need to enter to install the Node dependencies and start the app.

+ +
+

The new app will have a package.json file in its root directory. You can open this to see what dependencies are installed, including Express and the template library Jade:

+ +
{
+  "name": "helloworld",
+  "version": "0.0.0",
+  "private": true,
+  "scripts": {
+    "start": "node ./bin/www"
+  },
+  "dependencies": {
+    "body-parser": "~1.18.2",
+    "cookie-parser": "~1.4.3",
+    "debug": "~2.6.9",
+    "express": "~4.15.5",
+    "jade": "~1.11.0",
+    "morgan": "~1.9.0",
+    "serve-favicon": "~2.4.5"
+  }
+}
+ +

 

+
+ +

Install all the dependencies for the helloworld app using NPM as shown:

+ +
cd helloworld
+npm install
+
+ +

Then run the app (the commands are slightly different for Windows and Linux/macOS), as shown below:

+ +
# Run the helloworld on Windows
+SET DEBUG=helloworld:* & npm start
+
+# Run helloworld on Linux/macOS
+DEBUG=helloworld:* npm start
+
+ +

The DEBUG command creates useful logging, resulting in an output like that shown below.

+ +
>SET DEBUG=helloworld:* & npm start
+
+> helloworld@0.0.0 start D:\Github\expresstests\helloworld
+> node ./bin/www
+
+  helloworld:server Listening on port 3000 +0ms
+ +

Open a browser and navigate to http://127.0.0.1:3000/ to see the default Express welcome page.

+ +

Express - Generated App Default Screen

+ +

We'll talk more about the generated app when we get to the article on generating a skeleton application.

+ + + +

Resumo

+ +

You now have a Node development environment up and running on your computer that can be used for creating Express web applications. You've also seen how NPM can be used to import Express into an application, and also how you can create applications using the Express Application Generator tool and then run them.

+ +

In the next article we start working through a tutorial to build a complete web application using this environment and associated tools.

+ +

Consulte também

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}

+ +

 

+ +

Neste módulop

+ + + +

 

diff --git a/files/pt-pt/learn/server-side/express_nodejs/index.html b/files/pt-pt/learn/server-side/express_nodejs/index.html new file mode 100644 index 0000000000..1c7e7413ec --- /dev/null +++ b/files/pt-pt/learn/server-side/express_nodejs/index.html @@ -0,0 +1,76 @@ +--- +title: Framework da Web Express (Node.js/JavaScript) +slug: Learn/No-servidor/Express_Nodejs +tags: + - Aprender + - CodingScripting + - Express + - Express.js + - Introdução + - JavaScript + - Node + - Nodo + - Principiante + - Programação no lado do servidor + - node.js +translation_of: Learn/Server-side/Express_Nodejs +--- +
{{LearnSidebar}}
+ +

Express é uma das frameworks mais populares, escrita em JavaScript e hospedada dentro do próprio ambiente de execução node.js. Este módulo explica alguns dos benefícios chave desta framework, como configurar o seu ambiente de desenvolvimento e como realizar tarefas comuns de desenvolvimento da web e tarefas de implementação.

+ +

Pré-requisitos

+ +

Antes de iniciar este módulo, você precisará entender o que são os programas da web e do lado do servidor, idealmente lendo os tópicos no nosso módulo Os primeiros passos de programação do sites da Web no lado do servidor. Um conhecimento geral de conceitos de programação e JavaScript é altamente recomendado, mas não essencial para compreender os conceitos fundamentais.

+ +
+

Nota: This website has many useful resources for learning JavaScript in the context of client-side development: JavaScriptJavaScript Guide, JavaScript BasicsJavaScript (learning). The core JavaScript language and concepts are the same for server-side development on Node.js and this material will be relevant. Node.js offers additional APIs for supporting functionality that is useful in browserless environments, e.g. to create HTTP servers and access the file system, but does not support JavaScript APIs for working with the browser and DOM.

+ +

This guide will provide some information about working with Node.js and Express, and there are numerous other excellent resources on the Internet and in books — some of these linked from How do I get started with Node.js (StackOverflow) and What are the best resources for learning Node.js? (Quora).

+
+ +

Guias

+ +
+
Introdução a Express/Node
+
In this first Express article we answer the questions "What is Node?" and "What is Express?" and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).
+
Configurar um ambiente de desenvolvimento Node (Express)
+
Now that you know what Express is for, we'll show you how to set up and test a Node/Express development environment on Windows, Linux (Ubuntu), and Mac OS X. Whatever common operating system you are using, this article should give you what you need to be able to start developing Express apps.
+
Tutorial de Express: O Website - Biblioteca Local
+
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.
+
Tutorial de Express Parte 2: Criar um esqueleto de um website
+
This article shows how you can create a "skeleton" website project, which you can then go on to populate with site-specific routes, templates/views, and databases.
+
Tutorial de Express Parte 3: Usar uma Base de Dados (com Mongoose)
+
This article briefly introduces databases for Node/Express. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways you can access model data.
+
Tutorial de Express Parte 4: Rotas e controladores
+
In this tutorial we'll set up routes (URL handling code) with "dummy" handler functions for all the resource endpoints that we'll eventually need in the LocalLibrary website. On completion, we'll have a modular structure for our route handling code, that we can extend with real handler functions in the following articles. We'll also have a really good understanding of how to create modular routes using Express.
+
Tutorial de Express Parte 5: Exibir dados da biblioteca
+
We're now ready to add the pages that display the LocalLibrary website books and other data. The pages will include a home page that shows how many records we have of each model type, and list and detail pages for all of our models. Along the way we'll gain practical experience in getting records from the database, and using templates.
+
Tutorial de Express Parte 6: Trabalhar com formulários
+
In this tutorial we'll show you how to work with HTML Forms in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.
+
Tutorial de Express Parte 7: Enviar para produção
+
Now you've created an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
+
+ +

Consulte também

+ +
+
Installing LocalLibrary on PWS/Cloud Foundry
+
This article provides a practical demonstration of how to install LocalLibrary on the Pivotal Web Services PaaS cloud — this is a full-featured, open source alternative to Heroku, the PaaS cloud service used in Part 7 of the tutorial, listed above. PWS/Cloud Foundry is definitely worth checking out if you are looking for an alternative to Heroku (or another PaaS cloud service), or simply feel like trying something different.
+
+ +

Adicionar mais tutoriais

+ +
+

That's the end of the tutorial articles (for now). If you would like to extend it, other interesting topics to cover are:

+ + + +

And of course it would be excellent to have an assessment task!

+
diff --git a/files/pt-pt/learn/server-side/express_nodejs/introduction/index.html b/files/pt-pt/learn/server-side/express_nodejs/introduction/index.html new file mode 100644 index 0000000000..c39acc6f1d --- /dev/null +++ b/files/pt-pt/learn/server-side/express_nodejs/introduction/index.html @@ -0,0 +1,539 @@ +--- +title: Introdução a Express/Node +slug: Learn/No-servidor/Express_Nodejs/Introduction +tags: + - Aprender + - CodingScripting + - Express + - Nodo + - Principiante + - lado do servidor + - nodejs +translation_of: Learn/Server-side/Express_Nodejs/Introduction +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/No-servidor/Express_Nodejs", "Learn/Server-side/Express_Nodejs")}}
+ +

In this first Express article we answer the questions "What is Node?" (answer: a library) and "What is Express?", and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).

+ + + + + + + + + + + + +
Pré-requisitos:Basic computer literacy. A general understanding of server-side website programming, and in particular the mechanics of client-server interactions in websites.
Objetivo:To gain familiarity with what Express is and how it fits in with Node, what functionality it provides, and the main building blocks of an Express application.
+ +

Introdução a Node

+ +

Node (or more formally Node.js) is an open-source, cross-platform, runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS). As such, the environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs including HTTP and file system libraries.

+ +

From a web server development perspective Node has a number of benefits:

+ + + +

You can use Node.js to create a simple web server using the Node HTTP package.

+ +

Hello Node.js

+ +

The following example creates a web server that listens for any kind of HTTP request on the URL http://127.0.0.1:8000/ — when a request is received, the script will respond with the string: "Hello World". If you have already installed node, you can follow these steps to try out the example:

+ +
    +
  1. Open Terminal (on Windows, open the command line utility)
  2. +
  3. Create the folder where you want to save the program, for example, "test-node" and then enter it by entering the following command into your terminal:
  4. +
+ +
cd test-node
+ +
    +
  1. Using your favorite text editor, create a file called "hello.js" and paste the following code into it:
  2. +
+ +
// Load HTTP module
+var http = require("http");
+
+// Create HTTP server and listen on port 8000 for requests
+http.createServer(function(request, response) {
+
+   // Set the response HTTP header with HTTP status and Content type
+   response.writeHead(200, {'Content-Type': 'text/plain'});
+
+   // Send the response body "Hello World"
+   response.end('Hello World\n');
+}).listen(8000);
+
+// Print URL for accessing server
+console.log('Server running at http://127.0.0.1:8000/');
+ +
    +
  1. Save the file in the folder you created above.
  2. +
  3. Go back to the terminal and type the following command:
  4. +
+ +
node "hello.js"
+ +

Finally, navigate to "http://localhost:8000" in your web browser; you should see the text "Hello World" in the upper left of an otherwise empty web page.

+ +

Estruturas da Web (Frameworks)

+ +

Other common web-development tasks are not directly supported by Node itself. If you want to add specific handling for different HTTP verbs (e.g. GET, POST, DELETE, etc.), separately handle requests at different URL paths ("routes"), serve static files, or use templates to dynamically create the response, then you will need to write the code yourself, or you can avoid reinventing the wheel and use a web framework!

+ +

Introdução a Express

+ +

Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:

+ + + +

While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).

+ +
+

Nota: This flexibility is a double edged sword. There are middleware packages to address almost any problem or requirement, but working out the right packages to use can sometimes be a challenge. There is also no "right way" to structure an application, and many examples you might find on the Internet are not optimal, or only show a small part of what you need to do in order to develop a web application.

+
+ +

De onde veio o Node e o Express?

+ +

Node was initially released, for Linux only, in 2009. The NPM package manager was released in 2010, and native Windows support was added in 2012. The current LTS release is Node v8.11.2 while the latest release is Node 10.1.0. This is a tiny snapshot of a rich history; delve into Wikipedia if you want to know more.

+ +

Express was initially released in November 2010 and is currently on version 4.16 of the API. You can check out the changelog for information about changes in the current release, and GitHub for more detailed historical release notes.

+ +

Quão populares são o Node e Express?

+ +

The popularity of a web framework is important because it is an indicator of whether it will continue to be maintained, and what resources are likely to be available in terms of documentation, add-on libraries, and technical support.

+ +

There isn't any readily-available and definitive measurement of the popularity of server-side frameworks (although sites like Hot Frameworks attempt to assess popularity using mechanisms like counting the number of GitHub projects and StackOverflow questions for each platform). A better question is whether Node and Express are "popular enough" to avoid the problems of unpopular platforms. Are they continuing to evolve? Can you get help if you need it? Is there an opportunity for you to get paid work if you learn Express?

+ +

Based on the number of high profile companies that use Express, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, Express is a popular framework!

+ +

Express é opinativo?

+ +

Web frameworks often refer to themselves as "opinionated" or "unopinionated".

+ +

Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They often support rapid development in a particular domain (solving problems of a particular type) because the right way to do anything is usually well-understood and well-documented. However they can be less flexible at solving problems outside their main domain, and tend to offer fewer choices for what components and approaches they can use.

+ +

Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components together to achieve a goal, or even what components should be used. They make it easier for developers to use the most suitable tools to complete a particular task, albeit at the cost that you need to find those components yourself.
+
+ Express is unopinionated. You can insert almost any compatible middleware you like into the request handling chain, in almost any order you like. You can structure the app in one file or multiple files, and using any directory structure. You may sometimes feel that you have too many choices!

+ +

Como é que o código de Express se parece?

+ +

In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what action is needed based on the URL pattern and possibly associated information contained in POST data or GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.

+ +

Express provides methods to specify what function is called for a particular HTTP verb (GET, POST, SET, etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response. You can use Express middleware to add support for cookies, sessions, and users, getting POST/GET parameters, etc. You can use any database mechanism supported by Node (Express does not define any database-related behaviour).

+ +

The following sections explain some of the common things you'll see when working with Express and Node code.

+ +

Helloworld Express

+ +

First lets consider the standard Express Hello World example (we discuss each part of this below, and in the following sections).

+ +
+

Dica: If you have Node and Express already installed (or if you install them as shown in the next article), you can save this code in a text file called app.js and run it in a bash command prompt by calling:   

+ +

./node ./app.js

+
+ +
var express = require('express');
+var app = express();
+
+app.get('/', function(req, res) {
+  res.send('Hello World!');
+});
+
+app.listen(3000, function() {
+  console.log('Example app listening on port 3000!');
+});
+
+ +

The first two lines require() (import) the express module and create an Express application. This object, which is traditionally named app, has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering a template engine, and modifying application settings that control how the application behaves (e.g. the environment mode, whether route definitions are case sensitive, etc.)

+ +

The middle part of the code (the three lines starting with app.get) shows a route definition. The app.get() method specifies a callback function that will be invoked whenever there is an HTTP GET request with a path ('/') relative to the site root. The callback function takes a request and a response object as arguments, and simply calls send() on the response to return the string "Hello World!"

+ +

The final block starts up the server on port '3000' and prints a log comment to the console. With the server running, you could go to localhost:3000 in your browser to see the example response returned.

+ +

Importação e criação de módulos

+ +

A module is a JavaScript library/file that you can import into other code using Node's require() function. Express itself is a module, as are the middleware and database libraries that we use in our Express applications.

+ +

The code below shows how we import a module by name, using the Express framework as an example. First we invoke the require() function, specifying the name of the module as a string ('express'), and calling the returned object to create an Express application. We can then access the properties and functions of the application object.

+ +
var express = require('express');
+var app = express();
+
+ +

You can also create your own modules that can be imported in the same way.

+ +
+

Dica: You will want to create your own modules, because this allows you to organise your code into managable parts — a monolithic single-file application is hard to understand and maintain. Using modules also helps you manage your namespace, because only the variables you explicitly export are imported when you use a module.

+
+ +

To make objects available outside of a module you just need to assign them to the exports object. For example, the square.js module below is a file that exports area() and perimeter() methods:

+ +
exports.area = function(width) { return width * width; };
+exports.perimeter = function(width) { return 4 * width; };
+
+ +

We can import this module using require(), and then call the exported method(s) as shown:

+ +
var square = require('./square'); // Here we require() the name of the file without the (optional) .js file extension
+console.log('The area of a square with a width of 4 is ' + square.area(4));
+ +
+

Nota: You can also specify an absolute path to the module (or a name, as we did initially).

+
+ +

If you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports as shown below (you can also do this to make the root of the exports object a constructor or other function):

+ +
module.exports = {
+  area: function(width) {
+    return width * width;
+  },
+
+  perimeter: function(width) {
+    return 4 * width;
+  }
+};
+
+ +

For a lot more information about modules see Modules (Node API docs).

+ +

Utilizar APIs assíncronas

+ +

JavaScript code frequently uses asynchronous rather than synchronous APIs for operations that may take some time to complete. A synchronous API is one in which each operation must complete before the next operation can start. For example, the following log functions are synchronous, and will print the text to the console in order (First, Second).

+ +
console.log('First');
+console.log('Second');
+
+ +

By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the operation is complete). Once the operation finishes, the API will use some mechanism to perform additional operations. For example, the code below will print out "Second, First" because even though setTimeout() method is called first, and returns immediately, the operation doesn't complete for several seconds.

+ +
setTimeout(function() {
+   console.log('First');
+   }, 3000);
+console.log('Second');
+
+ +

Using non-blocking asynchronous APIs is even more important on Node than in the browser, because Node is a single threaded event-driven execution environment. "single threaded" means that all requests to the server are run on the same thread (rather than being spawned off into separate processes). This model is extremely efficient in terms of speed and server resources, but it does mean that if any of your functions call synchronous methods that take a long time to complete, they will block not just the current request, but every other request being handled by your web application.

+ +

There are a number of ways for an asynchronous API to notify your application that it has completed. The most common way is to register a callback function when you invoke the asynchronous API, that will be called back when the operation completes. This is the approach used above.

+ +
+

Dica: Using callbacks can be quite "messy" if you have a sequence of dependent asynchronous operations that must be performed in order, because this results in multiple levels of nested callbacks. This problem is commonly known as "callback hell". This problem can be reduced by good coding practices (see http://callbackhell.com/), using a module like async, or even moving to ES6 features like Promises.

+
+ +
+

Nota: A common convention for Node and Express is to use error-first callbacks. In this convention the first value in your callback functions is an error value, while subsequent arguments contain success data. There is a good explanation of why this approach is useful in this blog: The Node.js Way - Understanding Error-First Callbacks (fredkschott.com).

+
+ +

Criação de manipuladores de rota

+ +

In our Hello World Express example (see above), we defined a (callback) route handler function for HTTP GET requests to the site root ('/').

+ +
app.get('/', function(req, res) {
+  res.send('Hello World!');
+});
+
+ +

The callback function takes a request and a response object as arguments. In this case the method simply calls send() on the response to return the string "Hello World!" There are a number of other response methods for ending the request/response cycle, for example you could call res.json() to send a JSON response or res.sendFile() to send a file.

+ +
+

Dica de JavaScript: You can use any argument names you like in the callback functions; when the callback is invoked the first argument will always be the request and the second will always be the response. It makes sense to name them such that you can identify the object you're working with in the body of the callback.

+
+ +

The Express application object also provides methods to define route handlers for all the other HTTP verbs, which are mostly used in exactly the same way: post(), put(), delete(), options(), trace(), copy(), lock(), mkcol(), move(), purge(), propfind(), proppatch(), unlock(), report(), mkactivity(), checkout(), merge(), m-search(), notify(), subscribe(), unsubscribe(), patch(), search(), and connect().

+ +

There is a special routing method, app.all(), which will be called in response to any HTTP method. This is used for loading middleware functions at a particular path for all request methods. The following example (from the Express documentation) shows a handler that will be executed for requests to /secret irrespective of the HTTP verb used (provided it is supported by the http module).

+ +
app.all('/secret', function(req, res, next) {
+  console.log('Accessing the secret section ...');
+  next(); // pass control to the next handler
+});
+ +

Routes allow you to match particular patterns of characters in a URL, and extract some values from the URL and pass them as parameters to the route handler (as attributes of the request object passed as a parameter).

+ +

Often it is useful to group route handlers for a particular part of a site together and access them using a common route-prefix (e.g. a site with a Wiki might have all wiki-related routes in one file and have them accessed with a route prefix of /wiki/). In Express this is achieved by using the express.Router object. For example, we can create our wiki route in a module named wiki.js, and then export the Router object, as shown below:

+ +
// wiki.js - Wiki route module
+
+var express = require('express');
+var router = express.Router();
+
+// Home page route
+router.get('/', function(req, res) {
+  res.send('Wiki home page');
+});
+
+// About page route
+router.get('/about', function(req, res) {
+  res.send('About this wiki');
+});
+
+module.exports = router;
+
+ +
+

Note: Adding routes to the Router object is just like adding routes to the app object (as shown previously).

+
+ +

To use the router in our main app file we would then require() the route module (wiki.js), then call use() on the Express application to add the Router to the middleware handling path. The two routes will then be accessible from /wiki/ and /wiki/about/.

+ +
var wiki = require('./wiki.js');
+// ...
+app.use('/wiki', wiki);
+ +

We'll show you a lot more about working with routes, and in particular about using the Router, later on in the linked section Routes and controllers .

+ +

Utilização de middleware

+ +

Middleware is used extensively in Express apps, for tasks from serving static files to error handling, to compressing HTTP responses. Whereas route functions end the HTTP request-response cycle by returning some response to the HTTP client, middleware functions typically perform some operation on the request or response and then call the next function in the "stack", which might be more middleware or a route handler. The order in which middleware is called is up to the app developer.

+ +
+

Nota: The middleware can perform any operation, execute any code, make changes to the request and response object, and it can also end the request-response cycle. If it does not end the cycle then it must call next() to pass control to the next middleware function (or the request will be left hanging).

+
+ +

Most apps will use third-party middleware in order to simplify common web development tasks like working with cookies, sessions, user authentication, accessing request POST and JSON data, logging, etc. You can find a list of middleware packages maintained by the Express team (which also includes other popular 3rd party packages). Other Express packages are available on the NPM package manager.

+ +

To use third party middleware you first need to install it into your app using NPM. For example, to install the morgan HTTP request logger middleware, you'd do this:

+ +
$ npm install morgan
+
+ +

You could then call use() on the Express application object to add the middleware to the stack:

+ +
var express = require('express');
+var logger = require('morgan');
+var app = express();
+app.use(logger('dev'));
+...
+ +
+

Nota: Middleware and routing functions are called in the order that they are declared. For some middleware the order is important (for example if session middleware depends on cookie middleware, then the cookie handler must be added first). It is almost always the case that middleware is called before setting routes, or your route handlers will not have access to functionality added by your middleware.

+
+ +

You can write your own middleware functions, and you are likely to have to do so (if only to create error handling code). The only difference between a middleware function and a route handler callback is that middleware functions have a third argument next, which middleware functions are expected to call if they are not that which completes the request cycle (when the middleware function is called, this contains the next function that must be called).

+ +

You can add a middleware function to the processing chain with either app.use() or app.add(), depending on whether you want to apply the middleware to all responses or to responses with a particular HTTP verb (GET, POST, etc). You specify routes the same in both cases, though the route is optional when calling app.use().

+ +

The example below shows how you can add the middleware function using both methods, and with/without a route.

+ +
var express = require('express');
+var app = express();
+
+// An example middleware function
+var a_middleware_function = function(req, res, next) {
+  // ... perform some operations
+  next(); // Call next() so Express will call the next middleware function in the chain.
+}
+
+// Function added with use() for all routes and verbs
+app.use(a_middleware_function);
+
+// Function added with use() for a specific route
+app.use('/someroute', a_middleware_function);
+
+// A middleware function added for a specific HTTP verb and route
+app.get('/', a_middleware_function);
+
+app.listen(3000);
+ +
+

Dica de JavaScript: Above we declare the middleware function separately and then set it as the callback. In our previous route handler function we declared the callback function when it was used. In JavaScript, either approach is valid.

+
+ +

The Express documentation has a lot more excellent documentation about using and writing Express middleware.

+ +

Servindo ficheiros estásticos

+ +

You can use the express.static middleware to serve static files, including your images, CSS and JavaScript (static() is the only middleware function that is actually part of Express). For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named 'public' at the same level as where you call node:

+ +
app.use(express.static('public'));
+
+ +

Any files in the public directory are served by adding their filename (relative to the base "public" directory) to the base URL. So for example:

+ +
http://localhost:3000/images/dog.jpg
+http://localhost:3000/css/style.css
+http://localhost:3000/js/app.js
+http://localhost:3000/about.html
+
+ +

You can call static() multiple times to serve multiple directories. If a file cannot be found by one middleware function then it will simply be passed on to the subsequent middleware (the order that middleware is called is based on your declaration order).

+ +
app.use(express.static('public'));
+app.use(express.static('media'));
+
+ +

You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we specify a mount path so that the files are loaded with the prefix "/media":

+ +
app.use('/media', express.static('public'));
+
+ +

Now, you can load the files that are in the public directory from the /media path prefix.

+ +
http://localhost:3000/media/images/dog.jpg
+http://localhost:3000/media/video/cat.mp4
+http://localhost:3000/media/cry.mp3
+
+ +

For more information, see Serving static files in Express.

+ +

Erros de manipulação

+ +

Errors are handled by one or more special middleware functions that have four arguments, instead of the usual three: (err, req, res, next). For example:

+ +
app.use(function(err, req, res, next) {
+  console.error(err.stack);
+  res.status(500).send('Something broke!');
+});
+
+ +

These can return any content required, but must be called after all other app.use() and routes calls so that they are the last middleware in the request handling process!

+ +

Express comes with a built-in error handler, which takes care of any remaining errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack. If you pass an error to next() and you do not handle it in an error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace.

+ +
+

Nota: The stack trace is not included in the production environment. To run it in production mode you need to set the the environment variable NODE_ENV to 'production'.

+
+ +
+

Nota: HTTP404 and other "error" status codes are not treated as errors. If you want to handle these, you can add a middleware function to do so. For more information see the FAQ.

+
+ +

For more information see Error handling (Express docs).

+ +

Utilização de bases de dados

+ +

Express apps can use any database mechanism supported by Node (Express itself doesn't define any specific additional behaviour/requirements for database management). There are many options, including PostgreSQL, MySQL, Redis, SQLite, MongoDB, etc.

+ +

In order to use these you have to first install the database driver using NPM. For example, to install the driver for the popular NoSQL MongoDB you would use the command:

+ +
$ npm install mongodb
+
+ +

The database itself can be installed locally or on a cloud server. In your Express code you require the driver, connect to the database, and then perform create, read, update, and delete (CRUD) operations. The example below (from the Express documentation) shows how you can find "mammal" records using MongoDB.

+ +
//this works with older versions of  mongodb version ~ 2.2.33
+var MongoClient = require('mongodb').MongoClient;
+
+MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
+  if (err) throw err;
+
+  db.collection('mammals').find().toArray(function (err, result) {
+    if (err) throw err;
+
+    console.log(result);
+  });
+});
+
+
+//for mongodb version 3.0 and up
+let MongoClient = require('mongodb').MongoClient;
+MongoClient.connect('mongodb://localhost:27017/animals', function(err, client){
+   if(err) throw err;
+
+   let db = client.db('animals');
+   db.collection('mammals').find().toArray(function(err, result){
+     if(err) throw err;
+     console.log(result);
+     client.close();
+   });
+}
+
+ +

 

+ +

 

+ +

 

+ +

Another popular approach is to access your database indirectly, via an Object Relational Mapper ("ORM"). In this approach you define your data as "objects" or "models" and the ORM maps these through to the underlying database format. This approach has the benefit that as a developer you can continue to think in terms of JavaScript objects rather than database semantics, and that there is an obvious place to perform validation and checking of incoming data. We'll talk more about databases in a later article.

+ +

For more information see Database integration (Express docs).

+ +

Renderização de dados (visualizações)

+ +

Template engines (referred to as "view engines" by Express) allow you to specify the structure of an output document in a template, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of documents. Express has support for a number of template engines, and there is a useful comparison of the more popular engines here: Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More.

+ +

In your application settings code you set the template engine to use and the location where Express should look for templates using the 'views' and 'view engines' settings, as shown below (you will also have to install the package containing your template library too!)

+ +
var express = require('express');
+var app = express();
+
+// Set directory to contain the templates ('views')
+app.set('views', path.join(__dirname, 'views'));
+
+// Set view engine to use, in this case 'some_template_engine_name'
+app.set('view engine', 'some_template_engine_name');
+
+ +

The appearance of the template will depend on what engine you use. Assuming that you have a template file named "index.<template_extension>" that contains placeholders for data variables named 'title' and "message", you would call Response.render() in a route handler function to create and send the HTML response:

+ +
app.get('/', function(req, res) {
+  res.render('index', { title: 'About dogs', message: 'Dogs rock!' });
+});
+ +

For more information see Using template engines with Express (Express docs).

+ +

Estrutura de ficheiro

+ +

Express makes no assumptions in terms of structure or what components you use. Routes, views, static files, and other application-specific logic can live in any number of files with any directory structure. While it is perfectly possible to have the whole Express application in one file, typically it makes sense to split your application into files based on function (e.g. account management, blogs, discussion boards) and architectural problem domain (e.g. model, view or controller if you happen to be using an MVC architecture).

+ +

In a later topic we'll use the Express Application Generator, which creates a modular app skeleton that we can easily extend for creating web applications.

+ + + +

Resumo

+ +

Congratulations, you've completed the first step in your Express/Node journey! You should now understand Express and Node's main benefits, and roughly what the main parts of an Express app might look like (routes, middleware, error handling, and template code). You should also understand that with Express being an unopinionated framework, the way you pull these parts together and the libraries that you use are largely up to you!

+ +

Of course Express is deliberately a very lightweight web application framework, so much of its benefit and potential comes from third party libraries and features. We'll look at those in more detail in the following articles. In our next article we're going to look at setting up a Node development environment, so that you can start seeing some Express code in action.

+ +

Consulte também

+ + + +
{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}
+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/server-side/index.html b/files/pt-pt/learn/server-side/index.html new file mode 100644 index 0000000000..b8cc8d35f7 --- /dev/null +++ b/files/pt-pt/learn/server-side/index.html @@ -0,0 +1,57 @@ +--- +title: Programação do site da Web no lado do servidor +slug: Learn/No-servidor +tags: + - Aprender + - Código + - Iniciante + - Introdução + - Programação no servidor + - Scripting + - Servidor + - Tópico +translation_of: Learn/Server-side +--- +
{{LearnSidebar}}
+ +

O tópico Sites da Web Dinâmicos - Programação no lado do servidor é uma série de módulos que mostram como criar sites da web dinâmicos; sites da web que entregam informação personalizada em resposta aos pedidos de HTTP. Os módulos proporcionam uma introdução genérica à programação no lado do servidor, bem como guias especificamente desenvolvidos para principiantes sobre como utilizar as estruturas de Django (Python) e Express (Node.js/JavaScript) para criar aplicações básicas.

+ +

A maioria dos maiores sites da web utilizam algum tipo de tecnologia no lado do servidor para exibir dados diferentes, conforme o necessário. Por exemplo, imagine quantos produtos é que estão disponíveis na Amazon e imagine quantos artigos é que foram escritos no Facebook? Exibir todo este conteúdo utilizando páginas estáticas completamente diferentes seria absolutamente ineficiente, assim em vez disso, estes sites exibem modelos estáticos (criados utilizando CSS, HTML e JavaScript), e depois atualizam os dados dinamicamente, exibindo-os dentro dos modelos quando necessário, por exemplo, quando tenta ver um produto diferente na Amazon.

+ +

No mundo moderno do desenvolvimento da web, aprender sobre o desenvolvimento no lado do servidor é altamente recomendado.

+ +

Caminho de aprendizagem

+ +

Começar com programação web no servidor é, de um modo geral, mais fácil que começar com desenvolvimento no lado do cliente, pois páginas web dinâmicas tendem a executar operações muito similares (adquirir dados e guardar na base de dados, verificar as permissões dos usuários, registrar usuários, etc.) , e são construídos utilizando frameworks, os quais tornam estas e outras operações de servidores web fáceis.

+ +

Ter conhecimentos básicos de conceitos de programação (ou de uma linguagem de programação específica) é útil, mas não essencial. Da mesma forma, experiência com código do lado do cliente não é absolutamente necessária, mas um conhecimento básico irá ajuda-lo a trabalhar melhor com os desenvolvedores que criam o "front-end" do seu website.

+ +

Precisará de compreender "como a web funciona". Recomendamos que comece por ler os seguintes tópicos:

+ + + +

Com a compreensão básica destes conceitos, estará pronto para continuar no seu caminho pelos módulos nesta secção.

+ +

Módulos

+ +

This topic contains the following modules. You should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks . 

+ +
+
Primeiros passos na programação web em servidores
+
This module provides server-technology-agnostic information about server-side website programming, including answers to fundamental questions about server-side programming — "what it is", "how it differs from client-side programming", and "why it is so useful" — and an overview of some of the more popular server-side web frameworks and guidance on how to select the most suitable for your site. Lastly we provide an introductory section on web server security.
+
Framework da Web Django (Python)
+
Django is an extremely popular and fully featured server-side web framework, written in Python. The module explains why Django is such a good web server framework, how to set up a development environment and how to perform common tasks with it.
+
Express Web Framework (Node.js/JavaScript)
+
Express is a popular web framework, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.
+
+ +

Consulte também

+ +
+
Servidor de Node sem uma framework
+
Este artigo fornece um servidor de ficheiros estático simples criado com Node.js puro, para aqueles que não desejam utilizar uma framework.
+
diff --git a/files/pt-pt/learn/server-side/node_server_without_framework/index.html b/files/pt-pt/learn/server-side/node_server_without_framework/index.html new file mode 100644 index 0000000000..85bd786b58 --- /dev/null +++ b/files/pt-pt/learn/server-side/node_server_without_framework/index.html @@ -0,0 +1,94 @@ +--- +title: Servidor de Node.js sem uma framework +slug: Learn/No-servidor/Servidor_node_sem_framework +tags: + - JavaScript + - Nodo + - Precisa de Conteúdo + - Servidor + - sem estrutura +translation_of: Learn/Server-side/Node_server_without_framework +--- +
{{LearnSidebar}}
+ +

 

+ +

Este artigo fornece um servidor de ficheiros estático simples com Node.js puro, sem a utilização de uma framework.

+ +

NodeJS tem muitas frameworks para ajudá-lo a ter o seu servidor configurado e a funcionar.

+ + + +

Estas não irão corresponder a todas as situações. Um programador pode precisar de criar o seu próprio servidor sem outras dependências.

+ +

Exemplo

+ +

Um servidor de ficheiros estático simples, criado com Node.js:

+ +

 

+ +
var http = require('http');
+var fs = require('fs');
+var path = require('path');
+
+http.createServer(function (request, response) {
+    console.log('request ', request.url);
+
+    var filePath = '.' + request.url;
+    if (filePath == './') {
+        filePath = './index.html';
+    }
+
+    var extname = String(path.extname(filePath)).toLowerCase();
+    var contentType = 'text/html';
+    var mimeTypes = {
+        '.html': 'text/html',
+        '.js': 'text/javascript',
+        '.css': 'text/css',
+        '.json': 'application/json',
+        '.png': 'image/png',
+        '.jpg': 'image/jpg',
+        '.gif': 'image/gif',
+        '.wav': 'audio/wav',
+        '.mp4': 'video/mp4',
+        '.woff': 'application/font-woff',
+        '.ttf': 'application/font-ttf',
+        '.eot': 'application/vnd.ms-fontobject',
+        '.otf': 'application/font-otf',
+        '.svg': 'application/image/svg+xml'
+    };
+
+    contentType = mimeTypes[extname] || 'application/octet-stream';
+
+    fs.readFile(filePath, function(error, content) {
+        if (error) {
+            if(error.code == 'ENOENT'){
+                fs.readFile('./404.html', function(error, content) {
+                    response.writeHead(200, { 'Content-Type': contentType });
+                    response.end(content, 'utf-8');
+                });
+            }
+            else {
+                response.writeHead(500);
+                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
+                response.end();
+            }
+        }
+        else {
+            response.writeHead(200, { 'Content-Type': contentType });
+            response.end(content, 'utf-8');
+        }
+    });
+
+}).listen(8125);
+console.log('Server running at http://127.0.0.1:8125/');
+ +

 

+ +

A efetuar

+ +

Estenda este artigo, explicando como é que o código acima funciona. Talvez, uma versão estendida que sirva os ficheiros estáticos e lide com pedidos dinâmicos.

diff --git a/files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html b/files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html new file mode 100644 index 0000000000..c50c8854ba --- /dev/null +++ b/files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html @@ -0,0 +1,607 @@ +--- +title: Como tratar de problemas de acessibilidade comuns +slug: Learn/Tools_and_testing/Teste_cruzado_de_navegador/Acessibilidade +translation_of: Learn/Tools_and_testing/Cross_browser_testing/Accessibility +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}
+ +

Neste módulo, vamos falar de acessibilidade, abordando problemas frequentes, como fazer testes simples, e como utilizar ferramentas de automatização e auditoria para identificar problemas de acessibilidade.

+ + + + + + + + + + + + +
Pré-requisitos:Familiaridade com as bases de HTML, CSS, e JavaScript; uma ideia-base dos princípios de testes cross browser de alto nível.
Objetivo:Saber diagnosticar problemas comuns de acessibilidade, e saber usar as ferramentas e técnicas adequadas para resolvê-los.
+ +

O que é acessibilidade?

+ +

When we say accessibility in the context of web technology, most people immediately think of making sure websites/apps are usable by people with disabilities, for example:

+ + + +

However, it is wrong to say that accessibility is just about disabilities. Really, the aim of accessibility is to make your websites/apps usable by as many people in as many contexts as possible, not just those users using high-powered desktop computers. Some examples might include:

+ + + +

In a way, this whole module is about accessibility — cross browser testing makes sure that your sites can be used by as many people as possible. What is accessibility? defines accessibility more completely and thoroughly than this article does.

+ +

That said, this article will cover cross browser and testing issues surrounding people with disabilities, and how they use the Web. We've already talked about other spheres such as responsive design and performance in other places in the module.

+ +
+

Note: Like many things in web development, accessibility isn't about 100% success or not; 100% accessibility is pretty much impossible to achieve for all content, especially as sites get more complex. Instead, it is more about making a reasonable effort to make as much of your content accessible to as many people as possible via defensive coding and sticking to best practices.

+
+ +

Common accessibility issues

+ +

In this section we'll detail some of the main issues that arise around web accessibility, connected with specific technologies, along with best practices to follow, and some quick tests you can do to see if your sites are going in the right direction.

+ +
+

Note: Accessibility is morally the right thing to do, and good for business (numbers of disabled users, users on mobile devices, etc. present significant market segments), but it is also a legal requirement in many parts of the world to make web content accessible to people with disabilities. Read Accessibility guidelines and the law for more information.

+
+ +

HTML

+ +

Semantic HTML (where the elements are used for their correct purpose) is accessible right out of the box — such content is readable by sighted viewers (provided you don't do anything silly like make the text way too small or hide it using CSS), but will also be usable by assistive technologies like screen readers (apps that literally read out a web page to their user), and confer other advantages too.

+ +

Semantic structure

+ +

The most important quick win in semantic HTML is to use a structure of headings and paragraphs for your content; this is because screen reader users tend to use the headings of a document as signposts to find the content they need more quickly. If your content has no headings, all they will get is a huge wall of text with no signposts to find anything. Examples of bad and good HTML:

+ +
<font size="7">My heading</font>
+<br><br>
+This is the first section of my document.
+<br><br>
+I'll add another paragraph here too.
+<br><br>
+<font size="5">My subheading</font>
+<br><br>
+This is the first subsection of my document. I'd love people to be able to find this content!
+<br><br>
+<font size="5">My 2nd subheading</font>
+<br><br>
+This is the second subsection of my content. I think it is more interesting than the last one.
+ +
<h1>My heading</h1>
+
+<p>This is the first section of my document.</p>
+
+<p>I'll add another paragraph here too.</p>
+
+<h2>My subheading</h2>
+
+<p>This is the first subsection of my document. I'd love people to be able to find this content!</p>
+
+<h2>My 2nd subheading</h2>
+
+<p>This is the second subsection of my content. I think it is more interesting than the last one.</p>
+ +

In addition, your content should make logical sense in its source order — you can always place it where you want using CSS later on, but you should get the source order right to start with.

+ +

As a test, you can turn off a site's CSS and see how understandable it is without it. You could do this manually by just removing the CSS from your code, but the easiest way is to use browser features, for example:

+ + + +

Using native keyboard accessibility

+ +

Certain HTML features can be selected using only the keyboard — this is default behavior, available since the early days of the web. The elements that have this capability are the common ones that allow user to interact with web pages, namely links, {{htmlelement("button")}}s, and form elements like {{htmlelement("input")}}.

+ +

You can try this out using our native-keyboard-accessibility.html example (see the source code) — open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused.

+ +

+ +

You can then press Enter/Return to follow a focused link or press a button (we've included some JavaScript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the {{htmlelement("select")}} element can have its options displayed and cycled between using the up and down arrow keys).

+ +

Note that different browsers may have different keyboard control options available. Most modern browsers follow the tab pattern described above (you can also do Shift + Tab to move backwards through the focusable elements), but some browsers have their own idiosyncracies:

+ + + +
+

Important: You should perform this kind of test on any new page you write — make sure the functionality can be accessed by the keyboard.

+
+ +

This example highlights the importance of using the correct semantic element for the correct job. It is possible to style any element to look like a link or button with CSS, and to behave like a link or button with JavaScript, but they won't actually be links or buttons, and you'll lose a lot of the accessibility these elements give you for free. So don't do it if you can avoid it.

+ +

Another tip — as shown in our example, you can control how your focusable elements look when focused, using the :focus pseudo-class. It is a good idea to double up focus and hover styles, so your users get that visual clue that a control will do something when activated, whether they are using mouse or keyboard:

+ +
a:hover, input:hover, button:hover, select:hover,
+a:focus, input:focus, button:focus, select:focus {
+  font-weight: bold;
+}
+ +
+

Note: If you do decide to remove the default focus styling using CSS, make sure you replace it with something else that fits in with your design better — it is a very valuable accessiblity tool, and should not be removed.

+
+ +

Building in keyboard accessibility

+ +

Sometimes it is not possible to avoid losing keyboard accessibility. You might have inherited a site where the semantics are not very good (perhaps you've ended up with a horrible CMS that generates buttons made with <div>s), or you are using a complex control that does not have keyboard accessibility built in, like the HTML5 {{htmlelement("video")}} element (amazingly, Opera is the only browser that allows you to tab through the <video> element's default browser controls). You have a few options here:

+ +
    +
  1. Create custom controls using <button> elements (which we can tab to by default!) and JavaScript to wire up their functionality. See Creating a cross-browser video player for some good examples of this.
  2. +
  3. Create keyboard shortcuts via JavaScript, so functionality is activated when you press certain keys on the keyboard. See Desktop mouse and keyboard controls for some game-related examples that can be adapted for any purpose.
  4. +
  5. Use some interesting tactics to fake button behaviour. Take for example our fake-div-buttons.html example (see source code). Here we've given our fake <div> buttons the ability to be focused (including via tab) by giving each one the attribute tabindex="0" (see WebAIM's tabindex article for more really useful details). This allows us to tab to the buttons, but not to activate them via the Enter/Return key. To do that, we had to add the following bit of JavaScript trickery: +
    document.onkeydown = function(e) {
    +  if(e.keyCode === 13) { // The Enter/Return key
    +    document.activeElement.onclick(e);
    +  }
    +};
    + Here we add a listener to the document object to detect when a button has been pressed on the keyboard. We check what button was pressed via the event object's keyCode property; if it is the keycode that matches Return/Enter, we run the function stored in the button's onclick handler using document.activeElement.onclick(). activeElement gives us the element that is currently focused on the page.
  6. +
+ +
+

Note: This technique will only work if you set your original event handlers via event handler properties (e.g. onclick). addEventListener won't work. This is a lot of extra hassle to build the functionality back in. And there's bound to be other problems with it. Better to just use the right element for the right job in the first place.

+
+ +

Text alternatives

+ +

Text alternatives are very important for accessibility — if a person has a visual or hearing impairment that stops them being able to see or hear some content, then this is a problem. The simplest text alternative available is the humble alt attribute, which we should include on all images that contain relevant content. This should contain a description of the image that successfully conveys its meaning and content on the page, to be picked up by a screenreader and read out to the user.

+ +
+

Note: For more information, read Text alternatives.

+
+ +

Missing alt text can be tested for in a number of ways, for example using accessibility {{anch("Auditing tools")}}.

+ +

Alt text is slightly more complex for video and audio content. There is a way to define text tracks (e.g. subtitles) and display them when video is being played, in the form of the {{htmlelement("track")}} element, and the WebVTT format (see Adding captions and subtitles to HTML5 video for a detailed tutorial). Browser compatibility for these features is fairly good, but if you want to provide text alternatives for audio or support older browsers, a simple text transcript presented somewhere on the page or on a separate page might be a good idea.

+ +

Element relationships and context

+ +

There are certain features and best practices in HTML designed to provide context and relationships between elements where none otherwise exists. The three most common examples are links, form labels, and data tables.

+ +

The key to accessible link text is that people using screen readers will often use a common feature whereby they pull up a list of all the links on the page. In this case, the link text needs to make sense out of context. For example, a list of links labeled "click here", "click here", etc. is really bad for accessibility. It is better for link text to make sense in context and out of context.

+ +

Next on our list, the form {{htmlelement("label")}} element is one of the central features that allows us to make forms accessible. The trouble with forms is that you need labels to say what data should be entered into each form input. Each label needs to be included inside a {{htmlelement("label")}} to link it unambiguously to its partner form input (each <label> for attribute value needs to match the form element id value), and it will make sense even if the source order is not completely logical (which to be fair it should be).

+ +
+

Note: For more information about link text and form labels, read Meaningful text labels.

+
+ +

Finally, a quick word about data tables. A basic data table can be written with very simple markup (see bad-table.html live, and source), but this has problems — there is no way for a screen reader user to associate rows or columns together as groupings of data — to do this you need to know what the header rows are, and if they are heading up rows, columns, etc. This can only be done visually for such a table.

+ +

If you instead look at our punk-bands-complete.html example (live, source), you can see a few accessibility aids at work here, such as table headers ({{htmlelement("th")}} and scope attributes), {{htmlelement("caption")}} element, etc.

+ +
+

Note: For more information about accessible tables, read Accessible data tables.

+
+ +

CSS

+ +

CSS tends to provide a lot fewer fundamental accessibility features than HTML, but it can still do just as much damage to accessibility if used incorrectly. We have already mentioned a couple of accessibility tips involving CSS:

+ + + +

There are a few other considerations you should take into account.

+ +

Color and color contrast

+ +

When choosing a color scheme for your website, you should make sure that the text (foreground) color contrasts well with the background color. Your design might look cool, but it is no good if people with visual impairments like color blindness can't read your content. Use a tool like WebAIM's Color Contrast Checker to check whether your scheme is contrasting enough.

+ +

Another tip is to not rely on color alone for signposts/information, as this will be no good for those who can't see the color. Instead of marking required form fields in red, for example, mark them with an asterisk and in red.

+ +
+

Note: A high contrast ratio will also allow anyone using a smartphone or tablet with a glossy screen to better read pages when in a bright environment, such as sunlight.

+
+ +

Hiding content

+ +

There are many instances where a visual design will require that not all content is shown at once. For example, in our Tabbed info box example (see source code) we have three panels of information, but we are positioning them on top of one another and providing tabs that can be clicked to show each one (it is also keyboard accessible — you can alternatively use Tab and Enter/Return to select them).

+ +

+ +

Screen reader users don't care about any of this — they are happy with the content as long as the source order makes sense, and they can get to it all. Absolute positioning (as used in this example) is generally seen as one of the best mechanisms of hiding content for visual effect, because it doesn't stop screen readers from getting to it.

+ +

On the other hand, you shouldn't use {{cssxref("visibility")}}:hidden or {{cssxref("display")}}:none, because they do hide content from screenreaders. Unless of course, there is a good reason why you want this content to be hidden from screenreaders.

+ +
+

Note: Invisible Content Just for Screen Reader Users has a lot more useful detail surrounding this topic.

+
+ +

JavaScript

+ +

JavaScript has the same kind of problems as CSS with respect to accessibility — it can be disastrous for accessibility if used badly, or overused. We've already hinted at some accessibility problems related to JavaScript, mainly in the area of semantic HTML — you should always use appropriate semantic HTML to implement functionality wherever it is available, for example use links and buttons as appropriate. Don't use <div> elements with JavaScript code to fake functionality if at all possible — it is error prone, and more work than using the free functionality HTML gives you.

+ +

Simple functionality

+ +

Generally simple functionality should work with just the HTML in place — JavaScript should only be used to enhance functionality, not build it in entirely. Good uses of JavaScript include:

+ + + +
+

Note: WebAIM's Accessible JavaScript provides some useful further details about considerations for accessible JavaScript.

+
+ +

More complex JavaScript implementations can create issues with accessibility — you need to do what you can. For example, it would be unreasonable to expect you to make a complex 3D game written using WebGL 100% accessible to a blind person, but you could implement keyboard controls so it is usable by non-mouse users, and make the color scheme contrasting enough to be usable by those with color deficiencies.

+ +

Complex functionality

+ +

One of the main areas problematic for accessibility is complex apps that involve complicated form controls (such as date pickers) and dynamic content that is updated often and incrementally.

+ +

Non-native complicated form controls are problematic because they tend to involve a lot of nested <div>s, and the browser does not know what to do with them by default. If you are inventing them yourself, you need to make sure that they are keyboard accessible; if you are using some kind of third-party framework, carefully review the options available to see how accessible they are before diving in. Bootstrap looks to be fairly good for accessibility, for example, although Making Bootstrap a Little More Accessible by Rhiana Heath explores some of its issues (mainly related to color contrast), and looks at some solutions.

+ +

Regularly updated dynamic content can be a problem because screenreader users might miss it, especially if it updates unexpectedly. If you have a single-page app with a main content panel that is regularly updated using XMLHttpRequest or Fetch, a screenreader user might miss those updates.

+ +

WAI-ARIA

+ +

Do you need to use such complex functionality, or will plain old semantic HTML do instead? If you do need complexity, you should consider using WAI-ARIA (Accessible Rich Internet Applications), a specification that provides semantics (in the form of new HTML attributes) for items such as complex form controls and updating panels that can be understood by most browsers and screen readers.

+ +

To deal with complex form widgets, you need to use ARIA attributes like roles to state what role different elements have in a widget (for example, are they a tab, or a tab panel?), aria-disabled to say whether a control is disabled or not, etc.

+ +

To deal with regularly updating regions of content, you can use the aria-live attribute, which identifies an updating region. Its value indicates how urgently the screen reader should read it out:

+ + + +

Here's an example:

+ +
<p><span id="LiveRegion1" aria-live="polite" aria-atomic="false"></span></p>
+ +

You can see an example in action at Freedom Scientific's ARIA (Accessible Rich Internet Applications) Live Regions example — the highlighted paragraph should update its content every 10 seconds, and a screenreader should read this out to the user. ARIA Live Regions - Atomic provides another useful example.

+ +

We don't have space to cover WAI-ARIA in detail here, you can learn a lot more about it at WAI-ARIA basics.

+ +

Accessibility tools

+ +

Now we've covered accessibility considerations for different web technologies, including a few testing techniques (like keyboard navigation and color contrast checkers), let's have a look at other tools you can make use of when doing accessibility testing.

+ +

Auditing tools

+ +

There are a number of auditing tools available that you can feed your web pages into. They will look over them and return a list of accessibility issues present on the page. Examples include:

+ + + +

Let's look at an example, using Wave.

+ +
    +
  1. Go to the Wave homepage.
  2. +
  3. Enter the URL of our bad-semantics.html example into the text input at the top of the page (or the URL of another webpage you'd like to analyze) and press Analyse Your Webpage.
  4. +
  5. Check out the description of the accessibility problems on the results page (the icons you can click to see what problems are occuring where are rather useful).
  6. +
+ +
+

Note: Such tools aren't good enough to solve all your accessibility problems on their own. You'll need a combination of these, knowledge and experience, user testing, etc. to get a full picture.

+
+ +

Automation tools

+ +

Deque's aXe tool goes a bit further than the auditing tools we mentioned above. Like the others, it checks pages and returns accessibility errors. Its most immediately useful form is probably the browser extensions:

+ + + +

These add an accessibility tab to the browser developer tools. For example, we installed the Firefox version, then used it to audit our bad-table.html example. We got the following results:

+ +

+ +

aXe is also installable using npm, and can be integrated with task runners like Grunt and Gulp, automation frameworks like Selenium and Cucumber, unit testing frameworks like Jasmin, and more besides (again, see the main aXe page for details).

+ +

Screenreaders

+ +

It is definitely worth testing with a screenreader to get used to how severely visually impaired people use the Web. There are a number of screenreaders available:

+ + + +

Generally, screen readers are separate apps that run on the host operating system and can read not only web pages, but text in other apps as well. This is not always the case (ChromeVox is a browser extension), but usually. Screenreaders tend to act in slightly different ways and have different controls, so you'll have to consult the documentation for your chosen screen reader to get all of the details — saying that, they all work in basically the same sort of way.

+ +

Let's go through some tests with a couple of different screenreaders to give you a general idea of how they work and how to test with them.

+ +
+

Note: WebAIM's Designing for Screen Reader Compatibility provides some useful information about screenreader usage and what works best for screenreaders. Also see Screen Reader User Survey #6 Results for some interesting screenreader usage statistics.

+
+ +

VoiceOver

+ +

VoiceOver (VO) comes free with your Mac/iPhone/iPad, so it's useful for testing on desktop/mobile if you use Apple products. We'll be testing it on Mac OS X on a MacBook Pro.

+ +

To turn it on, press Cmd + F5. If you've not used VO before, you will be given a welcome screen where you can choose to start VO or not, and run through a rather useful tutorial to learn how to use it. To turn it off again, press Cmd + F5 again.

+ +
+

Note: You should go through the tutorial at least once — it is a really useful way to learn VO.

+
+ +

When VO is on, the display will look mostly the same, but you'll see a black box at the bottom left of the screen that contains information on what VO currently has selected. The current selection will also be highlighted, with a black border — this highlight is known as the VO cursor.

+ +

+ +

To use VO, you will make a lot of use of the "VO modifier" — this is a key or key combination that you need to press in addition to the actual VO keyboard shortcuts to get them to work. Using a modifier like this is common with screenreaders, to enable them to keep their commands from clashing with other commands. In the case of VO, the modifier can either be CapsLock, or Ctrl + Option.

+ +

VO has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "VO" means "the VoiceOver modifier".

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Most common VoiceOver keyboard shortcuts
Keyboard shortcutDescription
VO + Cursor keysMove the VO cursor up, right, down, left.
VO + SpacebarSelect/activate items highlighted by the VO cursor. This includes items selected in the Rotor (see below).
VO + Shift + down cursorMove into a group of items (such as an HTML table, or a form, etc.) Once inside a group you can move around and select items inside that group using the above commands as normal.
VO + Shift + up cursorMove out of a group.
VO + C(when inside a table) Read the header of the current column.
VO + R(when inside a table) Read the header of the current row.
VO + C + C (two Cs in succession)(when inside a table) Read the entire current column, including header.
VO + R + R (two Rs in succession)(when inside a table) Read the entire current row, including the headers that correspond to each cell.
VO + left cursor, VO + right cursor(when inside some horizontal options, such as a date or time picker) Move between options.
VO + up cursor, VO + down cursor(when inside some horizontal options, such as a date or time picker) Change the current option.
VO + UUse the Rotor, which displays lists of headings, links, form controls, etc. for easy navigation.
VO + left cursor, VO + right cursor(when inside Rotor) Move between different lists available in the Rotor.
VO + up cursor, VO + down cursor(when inside Rotor) Move between different items in the current Rotor list.
Esc(when inside Rotor) Exit Rotor.
Ctrl(when VO is speaking) Pause/Resume speech.
VO + ZRestart the last bit of speech.
VO + DGo into the Mac's Dock, so you can select apps to run inside it.
+ +

This seems like a lot of commands, but it isn't so bad when you get used to it, and VO regularly gives you reminders of what commands to use in certain places. Have a play with VO now; you can then go on to play with some of our examples in the {{anch("Screenreader testing")}} section.

+ +

NVDA

+ +

NVDA is Windows-only, and you'll need to install it.

+ +
    +
  1. Download it from nvaccess.org. You can choose whether to make a donation or download it for free; you'll also need to give them your e-mail address before you can download it.
  2. +
  3. Once downloaded, install it — you double click the installer, accept the license and follow the prompts.
  4. +
  5. To start NVDA, double click on the program file/shortcut, or use the keyboard shortcut Ctrl + Alt + N. You'll see the NVDA welcome dialog when you start it. Here you can choose from a couple of options, then press the OK button to get going.
  6. +
+ +

NVDA will now be active on your computer.

+ +

To use NVDA, you will make a lot of use of the "NVDA modifier" — this is a key that you need to press in addition to the actual NVDA keyboard shortcuts to get them to work. Using a modifier like this is common with screenreaders, to enable them to keep their commands from clashing with other commands. In the case of NVDA, the modifier can either be Insert (the default), or CapsLock (can be chosen by checking the first checkbox in the NVDA welcome dialog before pressing OK).

+ +
+

Note: NVDA is more subtle than VoiceOver in terms of how it highlights where it is and what it is doing. When you are scrolling through headings, lists, etc., items you are selected on will generally be highlighted with a subtle outline, but this is not always the case for all things. If you get completely lost, you can press Ctrl + F5 to refresh the current page and begin from the top again.

+
+ +

NVDA has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "NVDA" means "the NVDA modifier".

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Most common NVDA keyboard shortcuts
Keyboard shortcutDescription
NVDA + QTurn NVDA off again after you've started it.
NVDA + up cursorRead the current line.
NVDA + down cursorStart reading at the current position.
Up cursor and down cursor, or Shift + Tab and TabMove to previous/next item on page and read it.
Left cursor and right cursorMove to previous/next character in current item and read it.
Shift + H and HMove to previous/next heading and read it.
Shift + K and KMove to previous/next link and read it.
Shift + D and DMove to previous/next document landmark (e.g. <nav>) and read it.
Shift + 1–6 and 1–6Move to previous/next heading (level 1–6) and read it.
Shift + F and FMove to previous/next form input and focus on it.
Shift + T and TMove to previous/next data table and focus on it.
Shift + B and BMove to previous/next button and read its label.
Shift + L and LMove to previous/next list and read its first list item.
Shift + I and IMove to previous/next list item and read it.
Enter/Return(when link/button or other activatable item is selected) Activate item.
NVDA + Space(when form is selected) Enter form so individual items can be selected, or leave form if you are already in it.
Shift Tab and Tab(when inside form) Move between form inputs.
Up cursor and down cursor(when inside form) Change form input values (in the case of things like select boxes).
Spacebar(when inside form) Select chosen value.
Ctrl + Alt + cursor keys(when a table is selected) Move between table cells.
+ +

Screenreader testing

+ +

Now you've gotten used to using a screenreader, we'd like you to use it to do some quick accessibility tests, to get an idea of how screenreaders deal with good and bad webpage features:

+ + + +

User testing

+ +

As mentioned above, you can't rely on automated tools alone for determining accessibility problems on your site. It is recommended that when you draw up your testing plan, you should include some accessibility user groups if at all possible (see our User Testing section earlier on in the course for some more context). Try to get some screenreader users involved, some keyboard-only users, some non-hearing users, and perhaps other groups too, as suits your requirements.

+ +

Accessibility testing checklist

+ +

The following list provides a checklist for you to follow to make sure you've carried out the recommended accessibility testing for your project:

+ +
    +
  1. Make sure your HTML is as semantically correct as possible. Validating it is a good start, as is using an Auditing tool.
  2. +
  3. Check that your content makes sense when the CSS is turned off.
  4. +
  5. Make sure your functionality is keyboard accessible. Test using Tab, Return/Enter, etc.
  6. +
  7. Make sure your non-text content has text alternatives. An Auditing tool is good for catching such problems.
  8. +
  9. Make sure your site's color contrast is acceptable, using a suitable checking tool.
  10. +
  11. Make sure hidden content is visible by screenreaders.
  12. +
  13. Make sure that functionality is usable without JavaScript wherever possible.
  14. +
  15. Use ARIA to improve accessibility where appropriate.
  16. +
  17. Run your site through an Auditing tool.
  18. +
  19. Test it with a screenreader.
  20. +
  21. Include an accessibility policy/statement somewhere findable on your site to say what you did.
  22. +
+ +

Finding help

+ +

There are many other issues you'll encounter with accessibility; the most important thing to know really is how to find answers online. Consult the HTML and CSS article's Finding help section for some good pointers.

+ +

Summary

+ +

Hopefully this article has given you a good grounding in the main accessibility problems you might encounter, and how to test and overcome them.

+ +

In the next article we'll look at feature detection in more detail.

+ +

{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}

+ +

In this module

+ + diff --git a/files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html b/files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html new file mode 100644 index 0000000000..f788649424 --- /dev/null +++ b/files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html @@ -0,0 +1,47 @@ +--- +title: Teste cruzado de navegador +slug: Learn/Tools_and_testing/Teste_cruzado_de_navegador +tags: + - Acessibilidade + - Aprender + - Automação + - CSS + - CodingScripting + - Ferramentas + - HTML + - JavaScript + - Landing + - Principiante + - Testar + - cruzado navegador + - modulo +translation_of: Learn/Tools_and_testing/Cross_browser_testing +--- +
{{LearnSidebar}}
+ +

Este módulo foca-se em testar projetos da web em diferentes navegadores. Nós olhamos para identificar o seu público alvo (por exemplo, quais o s utilizadores, navegadores e dispositivos que mais precisa de se preocupar?), como testar, os principais problemas que irá enfrentar com diferentes tipos de código e como os mitigar, quais as ferramentas que são mais úteis para ajudá-lo a testar e corrigir problemas, e como utilizar a automação para acelerar os testes.

+ +

Pré-requisitos

+ +

You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here.

+ +

Guias

+ +
+
Introduction to cross browser testing
+
This article starts the module off by providing an overview of the topic of cross browser testing, answering questions such as "what is cross browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying, and fixing problems?"
+
Strategies for carrying out testing
+
Next, we drill down into carrying out testing, looking at identifying a target audience (e.g. what browsers, devices, and other segments should you make sure are tested), low fi testing strategies (get yourself a range of devices and some virtual machines and do adhoc tests when needed), higher tech strategies (automation, using dedicated testing apps), and testing with user groups.
+
Handling common HTML and CSS problems
+
With the scene set, we'll now look specifically at the common cross browser problems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handing CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
+
Handling common JavaScript problems
+
Now we'll look at common cross browser JavaScript problems and how to fix them. This includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern JavaScript features working in older browsers, and more.
+
Handling common accessibility problems
+
Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues.
+
Implementing feature detection
+
Feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser can always provide a working experience rather crashing/erroring in some browsers. This article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as @supports.
+
Introduction to automated testing
+
Manually running tests on several browsers and devices, several times per day, can get tedious and time consuming. To handle this efficiently, you should become familiar with automation tools. In this article we look at what is available, how to use task runners, and the basics of how to use commercial browser test automation apps such as Sauce Labs and Browser Stack.
+
Setting up your own test automation environment
+
In this article, we will teach you how to install your own automation environment and run your own tests using Selenium/WebDriver and a testing library such as selenium-webdriver for Node. We will also look at how to integrate your local testing environment with commercial apps like the ones discussed in the previous article.
+
diff --git a/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/acessibilidade/index.html b/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/acessibilidade/index.html deleted file mode 100644 index c50c8854ba..0000000000 --- a/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/acessibilidade/index.html +++ /dev/null @@ -1,607 +0,0 @@ ---- -title: Como tratar de problemas de acessibilidade comuns -slug: Learn/Tools_and_testing/Teste_cruzado_de_navegador/Acessibilidade -translation_of: Learn/Tools_and_testing/Cross_browser_testing/Accessibility ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}
- -

Neste módulo, vamos falar de acessibilidade, abordando problemas frequentes, como fazer testes simples, e como utilizar ferramentas de automatização e auditoria para identificar problemas de acessibilidade.

- - - - - - - - - - - - -
Pré-requisitos:Familiaridade com as bases de HTML, CSS, e JavaScript; uma ideia-base dos princípios de testes cross browser de alto nível.
Objetivo:Saber diagnosticar problemas comuns de acessibilidade, e saber usar as ferramentas e técnicas adequadas para resolvê-los.
- -

O que é acessibilidade?

- -

When we say accessibility in the context of web technology, most people immediately think of making sure websites/apps are usable by people with disabilities, for example:

- - - -

However, it is wrong to say that accessibility is just about disabilities. Really, the aim of accessibility is to make your websites/apps usable by as many people in as many contexts as possible, not just those users using high-powered desktop computers. Some examples might include:

- - - -

In a way, this whole module is about accessibility — cross browser testing makes sure that your sites can be used by as many people as possible. What is accessibility? defines accessibility more completely and thoroughly than this article does.

- -

That said, this article will cover cross browser and testing issues surrounding people with disabilities, and how they use the Web. We've already talked about other spheres such as responsive design and performance in other places in the module.

- -
-

Note: Like many things in web development, accessibility isn't about 100% success or not; 100% accessibility is pretty much impossible to achieve for all content, especially as sites get more complex. Instead, it is more about making a reasonable effort to make as much of your content accessible to as many people as possible via defensive coding and sticking to best practices.

-
- -

Common accessibility issues

- -

In this section we'll detail some of the main issues that arise around web accessibility, connected with specific technologies, along with best practices to follow, and some quick tests you can do to see if your sites are going in the right direction.

- -
-

Note: Accessibility is morally the right thing to do, and good for business (numbers of disabled users, users on mobile devices, etc. present significant market segments), but it is also a legal requirement in many parts of the world to make web content accessible to people with disabilities. Read Accessibility guidelines and the law for more information.

-
- -

HTML

- -

Semantic HTML (where the elements are used for their correct purpose) is accessible right out of the box — such content is readable by sighted viewers (provided you don't do anything silly like make the text way too small or hide it using CSS), but will also be usable by assistive technologies like screen readers (apps that literally read out a web page to their user), and confer other advantages too.

- -

Semantic structure

- -

The most important quick win in semantic HTML is to use a structure of headings and paragraphs for your content; this is because screen reader users tend to use the headings of a document as signposts to find the content they need more quickly. If your content has no headings, all they will get is a huge wall of text with no signposts to find anything. Examples of bad and good HTML:

- -
<font size="7">My heading</font>
-<br><br>
-This is the first section of my document.
-<br><br>
-I'll add another paragraph here too.
-<br><br>
-<font size="5">My subheading</font>
-<br><br>
-This is the first subsection of my document. I'd love people to be able to find this content!
-<br><br>
-<font size="5">My 2nd subheading</font>
-<br><br>
-This is the second subsection of my content. I think it is more interesting than the last one.
- -
<h1>My heading</h1>
-
-<p>This is the first section of my document.</p>
-
-<p>I'll add another paragraph here too.</p>
-
-<h2>My subheading</h2>
-
-<p>This is the first subsection of my document. I'd love people to be able to find this content!</p>
-
-<h2>My 2nd subheading</h2>
-
-<p>This is the second subsection of my content. I think it is more interesting than the last one.</p>
- -

In addition, your content should make logical sense in its source order — you can always place it where you want using CSS later on, but you should get the source order right to start with.

- -

As a test, you can turn off a site's CSS and see how understandable it is without it. You could do this manually by just removing the CSS from your code, but the easiest way is to use browser features, for example:

- - - -

Using native keyboard accessibility

- -

Certain HTML features can be selected using only the keyboard — this is default behavior, available since the early days of the web. The elements that have this capability are the common ones that allow user to interact with web pages, namely links, {{htmlelement("button")}}s, and form elements like {{htmlelement("input")}}.

- -

You can try this out using our native-keyboard-accessibility.html example (see the source code) — open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused.

- -

- -

You can then press Enter/Return to follow a focused link or press a button (we've included some JavaScript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the {{htmlelement("select")}} element can have its options displayed and cycled between using the up and down arrow keys).

- -

Note that different browsers may have different keyboard control options available. Most modern browsers follow the tab pattern described above (you can also do Shift + Tab to move backwards through the focusable elements), but some browsers have their own idiosyncracies:

- - - -
-

Important: You should perform this kind of test on any new page you write — make sure the functionality can be accessed by the keyboard.

-
- -

This example highlights the importance of using the correct semantic element for the correct job. It is possible to style any element to look like a link or button with CSS, and to behave like a link or button with JavaScript, but they won't actually be links or buttons, and you'll lose a lot of the accessibility these elements give you for free. So don't do it if you can avoid it.

- -

Another tip — as shown in our example, you can control how your focusable elements look when focused, using the :focus pseudo-class. It is a good idea to double up focus and hover styles, so your users get that visual clue that a control will do something when activated, whether they are using mouse or keyboard:

- -
a:hover, input:hover, button:hover, select:hover,
-a:focus, input:focus, button:focus, select:focus {
-  font-weight: bold;
-}
- -
-

Note: If you do decide to remove the default focus styling using CSS, make sure you replace it with something else that fits in with your design better — it is a very valuable accessiblity tool, and should not be removed.

-
- -

Building in keyboard accessibility

- -

Sometimes it is not possible to avoid losing keyboard accessibility. You might have inherited a site where the semantics are not very good (perhaps you've ended up with a horrible CMS that generates buttons made with <div>s), or you are using a complex control that does not have keyboard accessibility built in, like the HTML5 {{htmlelement("video")}} element (amazingly, Opera is the only browser that allows you to tab through the <video> element's default browser controls). You have a few options here:

- -
    -
  1. Create custom controls using <button> elements (which we can tab to by default!) and JavaScript to wire up their functionality. See Creating a cross-browser video player for some good examples of this.
  2. -
  3. Create keyboard shortcuts via JavaScript, so functionality is activated when you press certain keys on the keyboard. See Desktop mouse and keyboard controls for some game-related examples that can be adapted for any purpose.
  4. -
  5. Use some interesting tactics to fake button behaviour. Take for example our fake-div-buttons.html example (see source code). Here we've given our fake <div> buttons the ability to be focused (including via tab) by giving each one the attribute tabindex="0" (see WebAIM's tabindex article for more really useful details). This allows us to tab to the buttons, but not to activate them via the Enter/Return key. To do that, we had to add the following bit of JavaScript trickery: -
    document.onkeydown = function(e) {
    -  if(e.keyCode === 13) { // The Enter/Return key
    -    document.activeElement.onclick(e);
    -  }
    -};
    - Here we add a listener to the document object to detect when a button has been pressed on the keyboard. We check what button was pressed via the event object's keyCode property; if it is the keycode that matches Return/Enter, we run the function stored in the button's onclick handler using document.activeElement.onclick(). activeElement gives us the element that is currently focused on the page.
  6. -
- -
-

Note: This technique will only work if you set your original event handlers via event handler properties (e.g. onclick). addEventListener won't work. This is a lot of extra hassle to build the functionality back in. And there's bound to be other problems with it. Better to just use the right element for the right job in the first place.

-
- -

Text alternatives

- -

Text alternatives are very important for accessibility — if a person has a visual or hearing impairment that stops them being able to see or hear some content, then this is a problem. The simplest text alternative available is the humble alt attribute, which we should include on all images that contain relevant content. This should contain a description of the image that successfully conveys its meaning and content on the page, to be picked up by a screenreader and read out to the user.

- -
-

Note: For more information, read Text alternatives.

-
- -

Missing alt text can be tested for in a number of ways, for example using accessibility {{anch("Auditing tools")}}.

- -

Alt text is slightly more complex for video and audio content. There is a way to define text tracks (e.g. subtitles) and display them when video is being played, in the form of the {{htmlelement("track")}} element, and the WebVTT format (see Adding captions and subtitles to HTML5 video for a detailed tutorial). Browser compatibility for these features is fairly good, but if you want to provide text alternatives for audio or support older browsers, a simple text transcript presented somewhere on the page or on a separate page might be a good idea.

- -

Element relationships and context

- -

There are certain features and best practices in HTML designed to provide context and relationships between elements where none otherwise exists. The three most common examples are links, form labels, and data tables.

- -

The key to accessible link text is that people using screen readers will often use a common feature whereby they pull up a list of all the links on the page. In this case, the link text needs to make sense out of context. For example, a list of links labeled "click here", "click here", etc. is really bad for accessibility. It is better for link text to make sense in context and out of context.

- -

Next on our list, the form {{htmlelement("label")}} element is one of the central features that allows us to make forms accessible. The trouble with forms is that you need labels to say what data should be entered into each form input. Each label needs to be included inside a {{htmlelement("label")}} to link it unambiguously to its partner form input (each <label> for attribute value needs to match the form element id value), and it will make sense even if the source order is not completely logical (which to be fair it should be).

- -
-

Note: For more information about link text and form labels, read Meaningful text labels.

-
- -

Finally, a quick word about data tables. A basic data table can be written with very simple markup (see bad-table.html live, and source), but this has problems — there is no way for a screen reader user to associate rows or columns together as groupings of data — to do this you need to know what the header rows are, and if they are heading up rows, columns, etc. This can only be done visually for such a table.

- -

If you instead look at our punk-bands-complete.html example (live, source), you can see a few accessibility aids at work here, such as table headers ({{htmlelement("th")}} and scope attributes), {{htmlelement("caption")}} element, etc.

- -
-

Note: For more information about accessible tables, read Accessible data tables.

-
- -

CSS

- -

CSS tends to provide a lot fewer fundamental accessibility features than HTML, but it can still do just as much damage to accessibility if used incorrectly. We have already mentioned a couple of accessibility tips involving CSS:

- - - -

There are a few other considerations you should take into account.

- -

Color and color contrast

- -

When choosing a color scheme for your website, you should make sure that the text (foreground) color contrasts well with the background color. Your design might look cool, but it is no good if people with visual impairments like color blindness can't read your content. Use a tool like WebAIM's Color Contrast Checker to check whether your scheme is contrasting enough.

- -

Another tip is to not rely on color alone for signposts/information, as this will be no good for those who can't see the color. Instead of marking required form fields in red, for example, mark them with an asterisk and in red.

- -
-

Note: A high contrast ratio will also allow anyone using a smartphone or tablet with a glossy screen to better read pages when in a bright environment, such as sunlight.

-
- -

Hiding content

- -

There are many instances where a visual design will require that not all content is shown at once. For example, in our Tabbed info box example (see source code) we have three panels of information, but we are positioning them on top of one another and providing tabs that can be clicked to show each one (it is also keyboard accessible — you can alternatively use Tab and Enter/Return to select them).

- -

- -

Screen reader users don't care about any of this — they are happy with the content as long as the source order makes sense, and they can get to it all. Absolute positioning (as used in this example) is generally seen as one of the best mechanisms of hiding content for visual effect, because it doesn't stop screen readers from getting to it.

- -

On the other hand, you shouldn't use {{cssxref("visibility")}}:hidden or {{cssxref("display")}}:none, because they do hide content from screenreaders. Unless of course, there is a good reason why you want this content to be hidden from screenreaders.

- -
-

Note: Invisible Content Just for Screen Reader Users has a lot more useful detail surrounding this topic.

-
- -

JavaScript

- -

JavaScript has the same kind of problems as CSS with respect to accessibility — it can be disastrous for accessibility if used badly, or overused. We've already hinted at some accessibility problems related to JavaScript, mainly in the area of semantic HTML — you should always use appropriate semantic HTML to implement functionality wherever it is available, for example use links and buttons as appropriate. Don't use <div> elements with JavaScript code to fake functionality if at all possible — it is error prone, and more work than using the free functionality HTML gives you.

- -

Simple functionality

- -

Generally simple functionality should work with just the HTML in place — JavaScript should only be used to enhance functionality, not build it in entirely. Good uses of JavaScript include:

- - - -
-

Note: WebAIM's Accessible JavaScript provides some useful further details about considerations for accessible JavaScript.

-
- -

More complex JavaScript implementations can create issues with accessibility — you need to do what you can. For example, it would be unreasonable to expect you to make a complex 3D game written using WebGL 100% accessible to a blind person, but you could implement keyboard controls so it is usable by non-mouse users, and make the color scheme contrasting enough to be usable by those with color deficiencies.

- -

Complex functionality

- -

One of the main areas problematic for accessibility is complex apps that involve complicated form controls (such as date pickers) and dynamic content that is updated often and incrementally.

- -

Non-native complicated form controls are problematic because they tend to involve a lot of nested <div>s, and the browser does not know what to do with them by default. If you are inventing them yourself, you need to make sure that they are keyboard accessible; if you are using some kind of third-party framework, carefully review the options available to see how accessible they are before diving in. Bootstrap looks to be fairly good for accessibility, for example, although Making Bootstrap a Little More Accessible by Rhiana Heath explores some of its issues (mainly related to color contrast), and looks at some solutions.

- -

Regularly updated dynamic content can be a problem because screenreader users might miss it, especially if it updates unexpectedly. If you have a single-page app with a main content panel that is regularly updated using XMLHttpRequest or Fetch, a screenreader user might miss those updates.

- -

WAI-ARIA

- -

Do you need to use such complex functionality, or will plain old semantic HTML do instead? If you do need complexity, you should consider using WAI-ARIA (Accessible Rich Internet Applications), a specification that provides semantics (in the form of new HTML attributes) for items such as complex form controls and updating panels that can be understood by most browsers and screen readers.

- -

To deal with complex form widgets, you need to use ARIA attributes like roles to state what role different elements have in a widget (for example, are they a tab, or a tab panel?), aria-disabled to say whether a control is disabled or not, etc.

- -

To deal with regularly updating regions of content, you can use the aria-live attribute, which identifies an updating region. Its value indicates how urgently the screen reader should read it out:

- - - -

Here's an example:

- -
<p><span id="LiveRegion1" aria-live="polite" aria-atomic="false"></span></p>
- -

You can see an example in action at Freedom Scientific's ARIA (Accessible Rich Internet Applications) Live Regions example — the highlighted paragraph should update its content every 10 seconds, and a screenreader should read this out to the user. ARIA Live Regions - Atomic provides another useful example.

- -

We don't have space to cover WAI-ARIA in detail here, you can learn a lot more about it at WAI-ARIA basics.

- -

Accessibility tools

- -

Now we've covered accessibility considerations for different web technologies, including a few testing techniques (like keyboard navigation and color contrast checkers), let's have a look at other tools you can make use of when doing accessibility testing.

- -

Auditing tools

- -

There are a number of auditing tools available that you can feed your web pages into. They will look over them and return a list of accessibility issues present on the page. Examples include:

- - - -

Let's look at an example, using Wave.

- -
    -
  1. Go to the Wave homepage.
  2. -
  3. Enter the URL of our bad-semantics.html example into the text input at the top of the page (or the URL of another webpage you'd like to analyze) and press Analyse Your Webpage.
  4. -
  5. Check out the description of the accessibility problems on the results page (the icons you can click to see what problems are occuring where are rather useful).
  6. -
- -
-

Note: Such tools aren't good enough to solve all your accessibility problems on their own. You'll need a combination of these, knowledge and experience, user testing, etc. to get a full picture.

-
- -

Automation tools

- -

Deque's aXe tool goes a bit further than the auditing tools we mentioned above. Like the others, it checks pages and returns accessibility errors. Its most immediately useful form is probably the browser extensions:

- - - -

These add an accessibility tab to the browser developer tools. For example, we installed the Firefox version, then used it to audit our bad-table.html example. We got the following results:

- -

- -

aXe is also installable using npm, and can be integrated with task runners like Grunt and Gulp, automation frameworks like Selenium and Cucumber, unit testing frameworks like Jasmin, and more besides (again, see the main aXe page for details).

- -

Screenreaders

- -

It is definitely worth testing with a screenreader to get used to how severely visually impaired people use the Web. There are a number of screenreaders available:

- - - -

Generally, screen readers are separate apps that run on the host operating system and can read not only web pages, but text in other apps as well. This is not always the case (ChromeVox is a browser extension), but usually. Screenreaders tend to act in slightly different ways and have different controls, so you'll have to consult the documentation for your chosen screen reader to get all of the details — saying that, they all work in basically the same sort of way.

- -

Let's go through some tests with a couple of different screenreaders to give you a general idea of how they work and how to test with them.

- -
-

Note: WebAIM's Designing for Screen Reader Compatibility provides some useful information about screenreader usage and what works best for screenreaders. Also see Screen Reader User Survey #6 Results for some interesting screenreader usage statistics.

-
- -

VoiceOver

- -

VoiceOver (VO) comes free with your Mac/iPhone/iPad, so it's useful for testing on desktop/mobile if you use Apple products. We'll be testing it on Mac OS X on a MacBook Pro.

- -

To turn it on, press Cmd + F5. If you've not used VO before, you will be given a welcome screen where you can choose to start VO or not, and run through a rather useful tutorial to learn how to use it. To turn it off again, press Cmd + F5 again.

- -
-

Note: You should go through the tutorial at least once — it is a really useful way to learn VO.

-
- -

When VO is on, the display will look mostly the same, but you'll see a black box at the bottom left of the screen that contains information on what VO currently has selected. The current selection will also be highlighted, with a black border — this highlight is known as the VO cursor.

- -

- -

To use VO, you will make a lot of use of the "VO modifier" — this is a key or key combination that you need to press in addition to the actual VO keyboard shortcuts to get them to work. Using a modifier like this is common with screenreaders, to enable them to keep their commands from clashing with other commands. In the case of VO, the modifier can either be CapsLock, or Ctrl + Option.

- -

VO has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "VO" means "the VoiceOver modifier".

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Most common VoiceOver keyboard shortcuts
Keyboard shortcutDescription
VO + Cursor keysMove the VO cursor up, right, down, left.
VO + SpacebarSelect/activate items highlighted by the VO cursor. This includes items selected in the Rotor (see below).
VO + Shift + down cursorMove into a group of items (such as an HTML table, or a form, etc.) Once inside a group you can move around and select items inside that group using the above commands as normal.
VO + Shift + up cursorMove out of a group.
VO + C(when inside a table) Read the header of the current column.
VO + R(when inside a table) Read the header of the current row.
VO + C + C (two Cs in succession)(when inside a table) Read the entire current column, including header.
VO + R + R (two Rs in succession)(when inside a table) Read the entire current row, including the headers that correspond to each cell.
VO + left cursor, VO + right cursor(when inside some horizontal options, such as a date or time picker) Move between options.
VO + up cursor, VO + down cursor(when inside some horizontal options, such as a date or time picker) Change the current option.
VO + UUse the Rotor, which displays lists of headings, links, form controls, etc. for easy navigation.
VO + left cursor, VO + right cursor(when inside Rotor) Move between different lists available in the Rotor.
VO + up cursor, VO + down cursor(when inside Rotor) Move between different items in the current Rotor list.
Esc(when inside Rotor) Exit Rotor.
Ctrl(when VO is speaking) Pause/Resume speech.
VO + ZRestart the last bit of speech.
VO + DGo into the Mac's Dock, so you can select apps to run inside it.
- -

This seems like a lot of commands, but it isn't so bad when you get used to it, and VO regularly gives you reminders of what commands to use in certain places. Have a play with VO now; you can then go on to play with some of our examples in the {{anch("Screenreader testing")}} section.

- -

NVDA

- -

NVDA is Windows-only, and you'll need to install it.

- -
    -
  1. Download it from nvaccess.org. You can choose whether to make a donation or download it for free; you'll also need to give them your e-mail address before you can download it.
  2. -
  3. Once downloaded, install it — you double click the installer, accept the license and follow the prompts.
  4. -
  5. To start NVDA, double click on the program file/shortcut, or use the keyboard shortcut Ctrl + Alt + N. You'll see the NVDA welcome dialog when you start it. Here you can choose from a couple of options, then press the OK button to get going.
  6. -
- -

NVDA will now be active on your computer.

- -

To use NVDA, you will make a lot of use of the "NVDA modifier" — this is a key that you need to press in addition to the actual NVDA keyboard shortcuts to get them to work. Using a modifier like this is common with screenreaders, to enable them to keep their commands from clashing with other commands. In the case of NVDA, the modifier can either be Insert (the default), or CapsLock (can be chosen by checking the first checkbox in the NVDA welcome dialog before pressing OK).

- -
-

Note: NVDA is more subtle than VoiceOver in terms of how it highlights where it is and what it is doing. When you are scrolling through headings, lists, etc., items you are selected on will generally be highlighted with a subtle outline, but this is not always the case for all things. If you get completely lost, you can press Ctrl + F5 to refresh the current page and begin from the top again.

-
- -

NVDA has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "NVDA" means "the NVDA modifier".

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Most common NVDA keyboard shortcuts
Keyboard shortcutDescription
NVDA + QTurn NVDA off again after you've started it.
NVDA + up cursorRead the current line.
NVDA + down cursorStart reading at the current position.
Up cursor and down cursor, or Shift + Tab and TabMove to previous/next item on page and read it.
Left cursor and right cursorMove to previous/next character in current item and read it.
Shift + H and HMove to previous/next heading and read it.
Shift + K and KMove to previous/next link and read it.
Shift + D and DMove to previous/next document landmark (e.g. <nav>) and read it.
Shift + 1–6 and 1–6Move to previous/next heading (level 1–6) and read it.
Shift + F and FMove to previous/next form input and focus on it.
Shift + T and TMove to previous/next data table and focus on it.
Shift + B and BMove to previous/next button and read its label.
Shift + L and LMove to previous/next list and read its first list item.
Shift + I and IMove to previous/next list item and read it.
Enter/Return(when link/button or other activatable item is selected) Activate item.
NVDA + Space(when form is selected) Enter form so individual items can be selected, or leave form if you are already in it.
Shift Tab and Tab(when inside form) Move between form inputs.
Up cursor and down cursor(when inside form) Change form input values (in the case of things like select boxes).
Spacebar(when inside form) Select chosen value.
Ctrl + Alt + cursor keys(when a table is selected) Move between table cells.
- -

Screenreader testing

- -

Now you've gotten used to using a screenreader, we'd like you to use it to do some quick accessibility tests, to get an idea of how screenreaders deal with good and bad webpage features:

- - - -

User testing

- -

As mentioned above, you can't rely on automated tools alone for determining accessibility problems on your site. It is recommended that when you draw up your testing plan, you should include some accessibility user groups if at all possible (see our User Testing section earlier on in the course for some more context). Try to get some screenreader users involved, some keyboard-only users, some non-hearing users, and perhaps other groups too, as suits your requirements.

- -

Accessibility testing checklist

- -

The following list provides a checklist for you to follow to make sure you've carried out the recommended accessibility testing for your project:

- -
    -
  1. Make sure your HTML is as semantically correct as possible. Validating it is a good start, as is using an Auditing tool.
  2. -
  3. Check that your content makes sense when the CSS is turned off.
  4. -
  5. Make sure your functionality is keyboard accessible. Test using Tab, Return/Enter, etc.
  6. -
  7. Make sure your non-text content has text alternatives. An Auditing tool is good for catching such problems.
  8. -
  9. Make sure your site's color contrast is acceptable, using a suitable checking tool.
  10. -
  11. Make sure hidden content is visible by screenreaders.
  12. -
  13. Make sure that functionality is usable without JavaScript wherever possible.
  14. -
  15. Use ARIA to improve accessibility where appropriate.
  16. -
  17. Run your site through an Auditing tool.
  18. -
  19. Test it with a screenreader.
  20. -
  21. Include an accessibility policy/statement somewhere findable on your site to say what you did.
  22. -
- -

Finding help

- -

There are many other issues you'll encounter with accessibility; the most important thing to know really is how to find answers online. Consult the HTML and CSS article's Finding help section for some good pointers.

- -

Summary

- -

Hopefully this article has given you a good grounding in the main accessibility problems you might encounter, and how to test and overcome them.

- -

In the next article we'll look at feature detection in more detail.

- -

{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}

- -

In this module

- - diff --git a/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/index.html b/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/index.html deleted file mode 100644 index f788649424..0000000000 --- a/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Teste cruzado de navegador -slug: Learn/Tools_and_testing/Teste_cruzado_de_navegador -tags: - - Acessibilidade - - Aprender - - Automação - - CSS - - CodingScripting - - Ferramentas - - HTML - - JavaScript - - Landing - - Principiante - - Testar - - cruzado navegador - - modulo -translation_of: Learn/Tools_and_testing/Cross_browser_testing ---- -
{{LearnSidebar}}
- -

Este módulo foca-se em testar projetos da web em diferentes navegadores. Nós olhamos para identificar o seu público alvo (por exemplo, quais o s utilizadores, navegadores e dispositivos que mais precisa de se preocupar?), como testar, os principais problemas que irá enfrentar com diferentes tipos de código e como os mitigar, quais as ferramentas que são mais úteis para ajudá-lo a testar e corrigir problemas, e como utilizar a automação para acelerar os testes.

- -

Pré-requisitos

- -

You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here.

- -

Guias

- -
-
Introduction to cross browser testing
-
This article starts the module off by providing an overview of the topic of cross browser testing, answering questions such as "what is cross browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying, and fixing problems?"
-
Strategies for carrying out testing
-
Next, we drill down into carrying out testing, looking at identifying a target audience (e.g. what browsers, devices, and other segments should you make sure are tested), low fi testing strategies (get yourself a range of devices and some virtual machines and do adhoc tests when needed), higher tech strategies (automation, using dedicated testing apps), and testing with user groups.
-
Handling common HTML and CSS problems
-
With the scene set, we'll now look specifically at the common cross browser problems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handing CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
-
Handling common JavaScript problems
-
Now we'll look at common cross browser JavaScript problems and how to fix them. This includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern JavaScript features working in older browsers, and more.
-
Handling common accessibility problems
-
Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues.
-
Implementing feature detection
-
Feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser can always provide a working experience rather crashing/erroring in some browsers. This article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as @supports.
-
Introduction to automated testing
-
Manually running tests on several browsers and devices, several times per day, can get tedious and time consuming. To handle this efficiently, you should become familiar with automation tools. In this article we look at what is available, how to use task runners, and the basics of how to use commercial browser test automation apps such as Sauce Labs and Browser Stack.
-
Setting up your own test automation environment
-
In this article, we will teach you how to install your own automation environment and run your own tests using Selenium/WebDriver and a testing library such as selenium-webdriver for Node. We will also look at how to integrate your local testing environment with commercial apps like the ones discussed in the previous article.
-
-- cgit v1.2.3-54-g00ecf