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 --- .../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 +++++ 34 files changed, 5060 insertions(+), 5060 deletions(-) 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 (limited to 'files/pt-pt/learn/html') 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")}}

+ +
+ + + + + +
-- cgit v1.2.3-54-g00ecf