Создание документа HTML5. Структура HTML-документа: основные теги, пример

Последнее обновление: 08.04.2016

Элементы являются кирпичиками, из которых складывается документ html5. Для создания документа нам надо создать простой текстовый файл, а в качестве расширения файла указать *.html

Создадим текстовый файл, назовем его index и изменим его расширение на .html .

Затем откроем этот файл в любом текстовом редакторе, например, в Notepad++. Добавим в файл следующий текст:

Для создания документа HTML5 нам нужны в первую очередь два элемента: DOCTYPE и html. Элемент doctype или Document Type Declaration сообщает веб-браузеру тип документа. указывает, что данный документ является документом html и что используется html5, а не html4 или какая-то другая версия языка разметки.

А элемент html между своим открывающим и закрывающим тегами содержит все содержимое документа.

Внутри элемента html мы можем разместить два других элемента: head и body . Элемент head содержит метаданные веб-страницы - заголовок веб-страницы, тип кодировки и т.д., а также ссылки на внешние ресурсы - стили, скрипты, если они использутся. Элемент body собственно определяет содержимое html-страницы.

Теперь изменим содержимое файла index.html следующим образом:

Документ HTML5 Содержание документа HTML5

В элементе head определено два элемента:

    элемент title представляет заголовок страницы

    элемент meta определяет метаинформацию страницы. Для корректного отображения символов предпочтительно указывать кодировку. В данном случае с помощью атрибута charset="utf-8" указываем кодировку utf-8.

В пределах элемента элемента body используется только один элемент - div , который оформляет блок. Содержимым этого блока является простая строка.

Поскольку мы выбрали в качестве кодировки utf-8, то браузер будет отображать веб-страницу именно в этой кодировке. Однако необходимо чтобы сам текст документа также соответствовал выбранной кодировке utf-8. Как правило, в различных текстовых редакторах есть соотвествующие настройки для установки кодировки. Например, в Notepad++ надо зайти в меню Кодировки и в открывшемся списке выбрать пункт Преобразовать в UTF-8 без BOM :

После этого в статусной строке будет можно будет увидеть UTF-8 w/o BOM, что будет указывать, что нужная кодировка установлена.

Сохраним и откроем файл index.html в браузере:

Таким образом, мы создали первый документ HTML5. Так как мы указали в элементе title заголовок "Документ HTML5", то именно такое название будет иметь вкладка браузера.

Так как указана кодировка utf-8, то веб-браузер будет корректно отображать кириллические символы.

А весь текст, определенный внутри элемента body мы увидим в основном поле браузера.

HTML - расшифровывается как «язык гипертекстовой разметки» (англ. HyperText Markup Language), который является наиболее широко используемым языком для написания веб-страниц.

  • Гипертекст относится к способу связывания веб-страниц (HTML-документов). Таким образом, ссылка, доступная на веб-странице, называется гипертекстом.
  • Как следует из названия, HTML - это язык разметки, что означает, что Вы используете HTML, чтобы просто «разметить» текстовый документ с тегами, которые сообщают веб-браузеру, как структурировать его для отображения.

Первоначально HTML был разработан с целью определения структуры документов, таких как заголовки, списки, абзацы и так далее, чтобы облегчить обмен научной информацией между исследователями.

Теперь HTML широко используется для форматирования веб-страниц с помощью различных тегов, доступных на языке HTML.

HTML-документ

В следующем примере показан HTML-документ в простейшей форме:

Заголовок документа Заголовок

Здесь содержание документа...

Давайте сохраним код в HTML-файле document.html с помощью вашего любимого текстового редактора. И откройте файл с помощью веб-браузера, такого как Internet Explorer, Google Chrome или Firefox и др. Он должен показать следующий результат:

Теги для создания HTML-документа

Как уже говорилось ранее, HTML является языком разметки и использует различные теги для форматирования содержимого. Эти теги заключены в угловые скобки . Большинство тегов имеют соответствующие закрывающие теги, за исключением нескольких тегов. Например, тег имеет закрывающий тег и тег имеет тег закрытия и другие.

В приведенном выше примере используются следующие теги для создания HTML-документа:

Тег Описание
Этот тег определяет тип документа и версию HTML.
Этот тег охватывает полный HTML-документ и в основном состоит из заголовка документа, который представлен тегами ... и телом документа, которое представлено тегами ... .
Этот тег представляет заголовок документа, который может содержать другие html-теги, такие как , и т.д.
Тег используется внутри тега , чтобы указать название документа.
Этот тег представляет тело документа, в котором хранятся другие html-теги, такие как , ,

И другие.

Этот тег представляет заголовок.

Этот тег представляет абзац.

Знание этих тегов вполне хватит чтобы создать html-документ (html-страницу).

Чтобы изучить HTML, Вам нужно знать различные теги и понимать, как они ведут себя при форматировании текстового документа. Учить HTML легко, так как пользователям нужно только выучить использование разных тегов, чтобы отформатировать текст или изображения, тем самым сделать красивую веб-страницу.

Структура HTML-документа

Структура типичного HTML-документа будет иметь следующий вид:

Тег декларации документа Теги, связанные с заголовком документа Теги, связанные с телом документа

Мы изучим все теги заголовка и тела в последующих уроках, теперь давайте посмотрим, что такое тег декларации документа.

Декларация

Тег декларация используется веб-браузером для понимания версии HTML, используемой в документе. Текущая версия HTML - 5, и она использует следующее объявление:

Существует много других типов объявлений, которые могут использоваться в документе HTML в зависимости от того, какая версия HTML используется. Мы увидим более подробную информацию об этом при обсуждении тега вместе с другими тегами HTML.

При создании сайта первое, что нужно представлять — это то, как формируется веб-страница. Это, своего рода, «фундамент» в сайтостроении. Поэтому прежде чем, углубляться в изучение более сложных технологий создания сайтов, рекомендуется иметь хотя бы базовые сведения о HTML. В данном уроке мы познакомимся с HTML , разберем структуру документа HTML и на практических примерах закрепим полученные знания.

Что такое HTML?

HTML расшифровывается, как язык разметки гипертекста (от англ. HyperText Markup Language). Данный язык отвечает за то, как именно будет отображаться гипертекст на страницах сайта. Теперь давайте разберемся, что же такое гипертекст? Не секрет, что отдельная веб-страница может содержать много разнотипной информации, будь то текст, какие-то таблицы, графики, видеоролики, аудио и т.д. Так вот, всю эту информацию можно назвать одним словом — гипертекст.

Отметим, что HTML является именно языком разметки, а не языком программирования. В данном языке нет никаких логических функций и произвести какие-либо математические расчеты на нем невозможно. Страницы HTML имеют расширение .html или .htm и обрабатываются браузерами — IE, Mozilla Firefox, Google Chrome, Yandex Chrome, Opera и др.

Теперь давайте разберемся как же браузер понимает, что и каким образом отображать на веб-странице? Это очень просто. Язык разметки гипертекста HTML имеет встроенные команды, их называют тегами. Именно по ним браузер и ориентируются.

Структура документа HTML

Любой HTML документ (веб-станица) должен иметь определенную структуру. Это позволит избежать возможных проблем при открытии страниц в браузерах. В качестве примера давайте рассмотрим страницу, которая содержит следующих HTML код:

in another site).

POST request/response example

An HTTP POST is made when you submit a form containing information to be saved on the server.

The request

The text below shows the HTTP request made when a user submits new profile details on this site. The format of the request is almost the same as the GET request example shown previously, though the first line identifies this request as a POST .

1 Host: developer.mozilla..0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Content-Type: application/x-www-form-urlencoded Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0..8,es;q=0.6 Cookie: sessionid=6ynxs23n521lu21b1t136rhbv7ezngie; _gat=1; csrftoken=zIPUJsAZv6pcgCBJSCj1zU6pQZbfMUAT; dwf_section_edit=False; dwf_sg_task_completion=False; _ga=GA1.2.1688886003.1471911953; ffo=true csrfmiddlewaretoken=zIPUJsAZv6pcgCBJSCj1zU6pQZbfMUAT&user-username=hamishwillee&user-fullname=Hamish+Willee&user-title=&user-organization=&user-location=Australia&user-locale=en-US&user-timezone=Australia%2FMelbourne&user-irc_nickname=&user-interests=&user-expertise=&user-twitter_url=&user-stackoverflow_url=&user-linkedin_url=&user-mozillians_url=&user-facebook_url=

The main difference is that the URL doesn"t have any parameters. As you can see, the information from the form is encoded in the body of the request (for example, the new user fullname is set using: &user-fullname=Hamish+Willee).

The response

The response from the request is shown below. The status code of " 302 Found " tells the browser that the post succeeded, and that it must issue a second HTTP request to load the page specified in the Location field. The information is otherwise similar to that for the response to a GET request.

HTTP/1.1 302 FOUND Server: Apache X-Backend-Server: developer3.webapp.scl3.mozilla.com Vary: Cookie Vary: Accept-Encoding Content-Type: text/html; charset=utf-8 Date: Wed, 07 Sep 2016 00:38:13 GMT Location: https://сайт/en-US/profiles/hamishwillee Keep-Alive: timeout=5, max=1000 Connection: Keep-Alive X-Frame-Options: DENY X-Cache-Info: not cacheable; request wasn"t a GET or HEAD Content-Length: 0

Note : The HTTP responses and requests shown in these examples were captured using the Fiddler application, but you can get similar information using web sniffers (e.g. Websniffer) or browser extensions like HttpFox . You can try this yourself. Use any of the linked tools, and then navigate through a site and edit profile information to see the different requests and responses. Most modern browsers also have tools that monitor network requests (for example, the Network Monitor tool in Firefox).

Static sites

A static site is one that returns the same hard coded content from the server whenever a particular resource is requested. So for example if you have a page about a product at /static/myproduct1.html , this same page will be returned to every user. If you add another similar product to your site you will need to add another page (e.g. myproduct2.html) and so on. This can start to get really inefficient - what happens when you get to thousands of product pages? You would repeat a lot of code across each page (the basic page template, structure, etc.), and if you wanted to change anything about the page structure - like add a new "related products" section for example - then you"d have to change every page individually.

Note : Static sites are excellent when you have a small number of pages and you want to send the same content to every user. However they can have a significant cost to maintain as the number of pages becomes larger.

Let"s recap on how this works, by looking again at the static site architecture diagram we looked at in the last article.

When a user wants to navigate to a page, the browser sends an HTTP GET request specifying the URL of its HTML page. The server retrieves the requested document from its file system and returns an HTTP response containing the document and an HTTP Response status code of " 200 OK " (indicating success). The server might return a different status code, for example " 404 Not Found " if the file is not present on the server, or " 301 Moved Permanently " if the file exists but has been redirected to a different location.

The server for a static site will only ever need to process GET requests, because the server doesn"t store any modifiable data. It also doesn"t change its responses based on HTTP Request data (e.g. URL parameters or cookies).

Understanding how static sites work is nevertheless useful when learning server-side programming, because dynamic sites handle requests for static files (CSS, JavaScript, static images, etc.) in exactly the same way.

Dynamic sites

A dynamic site is one that can generate and return content based on the specific request URL and data (rather than always returning the same hard-coded file for a particular URL). Using the example of a product site, the server would store product "data" in a database rather than individual HTML files. When receiving an HTTP GET Request for a product, the server determines the product ID, fetches the data from the database, and then constructs the HTML page for the response by inserting the data into an HTML template. This has major advantages over a static site:

Using a database allows the product information to be stored efficiently in an easily extensible, modifiable, and searchable way.

Using HTML templates makes it very easy to change the HTML structure, because this only needs to be done in one place, in a single template, and not across potentially thousands of static pages.

Anatomy of a dynamic request

This section provides a step-by-step overview of the "dynamic" HTTP request and response cycle, building on what we looked at in the last article with much more detail. In order to "keep things real" we"ll use the context of a sports-team manager website where a coach can select their team name and team size in an HTML form and get back a suggested "best lineup" for their next game.

The diagram below shows the main elements of the "team coach" website, along with numbered labels for the sequence of operations when the coach accesses their "best team" list. The parts of the site that make it dynamic are the Web Application (this is how we will refer to the server-side code that processes HTTP requests and returns HTTP responses), the Database , which contains information about players, teams, coaches and their relationships, and the HTML Templates .

After the coach submits the form with the team name and number of players, the sequence of operations is:

  • The web browser creates an HTTP GET request to the server using the base URL for the resource (/best) and encoding the team and player number either as URL parameters (e.g. /best?team=my_team_name&show=11) or as part of the URL pattern (e.g. /best/my_team_name/11/). A GET request is used because the request is only fetching data (not modifying data).
  • The Web Server detects that the request is "dynamic" and forwards it to the Web Application for processing (the web server determines how to handle different URLs based on pattern matching rules defined in its configuration).
  • The Web Application identifies that the intention of the request is to get the "best team list" based on the URL (/best/) and finds out the required team name and number of players from the URL. The Web Application then gets the required information from the database (using additional "internal" parameters to define which players are "best", and possibly also getting the identity of the logged in coach from a client-side cookie).
  • The Web Application dynamically creates an HTML page by putting the data (from the Database ) into placeholders inside an HTML template.
  • The Web Application returns the generated HTML to the web browser (via the Web Server ), along with an HTTP status code of 200 ("success"). If anything prevents the HTML from being returned then the Web Application will return another code - for example "404" to indicate that the team does not exist.
  • The Web Browser will then start to process the returned HTML, sending separate requests to get any other CSS or JavaScript files that it references (see step 7).
  • The Web Server loads static files from the file system and returns them to the browser directly (again, correct file handling is based on configuration rules and URL pattern matching).
  • An operation to update a record in the database would be handled similarly, except that like any database update, the HTTP request from the browser should be encoded as a POST request.

    Doing other work

    A Web Application"s job is to receive HTTP requests and return HTTP responses. While interacting with a database to get or update information are very common tasks, the code may do other things at the same time, or not interact with a database at all.

    A good example of an additional task that a Web Application might perform would be sending an email to users to confirm their registration with the site. The site might also perform logging or other operations.

    Returning something other than HTML

    Server-side website code does not have to return HTML snippets/files in the response. It can instead dynamically create and return other types of files (text, PDF, CSV, etc.) or even data (JSON, XML, etc.).

    The idea of returning data to a web browser so that it can dynamically update its own content (AJAX) has been around for quite a while. More recently "Single-page apps" have become popular, where the whole website is written with a single HTML file that is dynamically updated when needed. Websites created using this style of application push a lot of computational cost from the server to the web browser, and can result in websites that appear to behave a lot more like native apps (highly responsive, etc.).

    Web frameworks simplify server-side web programming

    Server-side web frameworks make writing code to handle the operations described above much easier.

    One of the most important operations they perform is providing simple mechanisms to map URLs for different resources/pages to specific handler functions. This makes it easier to keep the code associated with each type of resource separate. It also has benefits in terms of maintenance, because you can change the URL used to deliver a particular feature in one place, without having to change the handler function.

    For example, consider the following Django (Python) code that maps two URL patterns to two view functions. The first pattern ensures that an HTTP request with a resource URL of /best will be passed to a function named index() in the views module. A request that has the pattern " /best/junior ", will instead be passed to the junior() view function.

    # file: best/urls.py # from django.conf.urls import url from . import views urlpatterns = [ # example: /best/ url(r"^$", views.index), # example: /best/junior/ url(r"^junior/$", views.junior), ]

    Note : The first parameters in the url() functions may look a bit odd (e.g. r"^junior/$") because they use a pattern matching technique called "regular expressions" (RegEx, or RE). You don"t need to know how regular expressions work at this point, other than that they allow us to match patterns in the URL (rather than the hard coded values above) and use them as parameters in our view functions. As an example, a really simple RegEx might say "match a single uppercase letter, followed by between 4 and 7 lower case letters."

    The web framework also makes it easy for a view function to fetch information from the database. The structure of our data is defined in models, which are Python classes that define the fields to be stored in the underlying database. If we have a model named Team with a field of "team_type " then we can use a simple query syntax to get back all teams that have a particular type.

    The example below gets a list of all teams that have the exact (case sensitive) team_type of "junior" - note the format: field name (team_type) followed by double underscore, and then the type of match to use (in this case exact). There are many other types of matches and we can daisy chain them. We can also control the order and the number of results returned.

    #best/views.py from django.shortcuts import render from .models import Team def junior(request): list_teams = Team.objects.filter(team_type__exact="junior") context = {"list": list_teams} return render(request, "best/index.html", context)

    After the junior() function gets the list of junior teams, it calls the render() function, passing the original HttpRequest , an HTML template, and a "context" object defining the information to be included in the template. The render() function is a convenience function that generates HTML using a context and an HTML template, and returns it in an HttpResponse object.

    Obviously web frameworks can help you with a lot of other tasks. We discuss a lot more benefits and some popular web framework choices in the next article.

    Summary

    At this point you should have a good overview of the operations that server-side code has to perform, and know some of the ways in which a server-side web framework can make this easier.

    In a following module we"ll help you choose the best Web Framework for your first site.



    
    Top