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

Из чего состоит структура HTML-документа

Тег сообщает о том, что начинается структура html-документа, — что заканчивается. Между тегами хранится в большей части информация для браузера и поисковых систем. В тегах содержится заголовок нашей страницы. Тег говорит о том, что далее идёт информация предназначенная для пользователя, же естесственно говорит о том, что информация для пользователя заканчивается.

Теперь немного поясню. Все теги (тэг — элемент языка разметки гипертекста ) делятся на два типа «одиночные» и «закрывающиеся». Кроме того теги заключаются в следующие символы < и > , именно они отличают тег от обычного текста html . Рассмотрим несколько самых простых «одиночных» тегов:


— тег, который отвечает за перенос на новую строку, в том месте, где установлен данный тег. Рассмотрим код с использованием этого тега.

Мой первый сайт Привет всем!
А это мой первый сайт.

Результат можно посмотреть .

— тег, который рисует горизонатльную линию. Этот тег относится к блочным элементам, линия всегда начинается с новой строки. Имеет 5 атрибутов:

  • align — Определяет выравнивание линии. Может принимать значение left, center, right.
  • color — Задаёт цвет линии.
  • noshade — Рисует линию без трехмерных эффектов.
  • size — Задаёт толщину линии.
  • width — Задаёт ширину линии.

Код с использованием тега :

Мой первый сайт Привет всем!А это мой первый сайт.

Визуальный пример находится .

Ещё один «одиночный» тег — это . Данный тег спользуются для хранения информации предназначенной для браузеров и поисковых систем. Поисковые системы обращаются к метатегам для получения описания сайта, ключевых слов и других данных. Разрешено использовать неограниченное число метатегов, все они должны находится между и . Параметры любого метатега имеют вид «имя=значение», который определяется ключевыми словами content , name или http-equiv . Т.к. метатеги предназначены для машин, никакого визуального изменения они не вносят, поэтому я приведу лишь исходный код:

Эта строка говорит о том, что создатель страницы считает, что на странице используется кодировка UTF-8. В HTML5 всё стало проще, для того, чтобы указать кодировку, достаточно лишь следующей строки:

Cуществуют и другие одиночные теги (, ,
, , , , , , , , , , , , , ), но с ними я познакомлю вас чуть позже.

Теперь давайте поговорим о «закрывающихся» тегах. Само название «закрывающийся тег», говорит о том, что тег требует обязательного закрытия. Это сделано для того, чтобы чётко ограничить часть текста, на которую действует тег.

Для наглядного примера взглянем на тег , который используется для выделения текста, он устанавливает жирное начертание шрифта. Теги и являются границами, которые определяют область выделения текста. Вот код, где в последней строке забыли закрыть тег :

Мой первый сайт Привет всем! А это мой первый сайт.
Привет всем! А это мой первый сайт.

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

Теги для выделения текста

Существует несколько способов выделить текст на странице. Сделать это можно с помощью стилей, а можно с помощью тегов. Нас (пока) интересует второй вариант.

— устанавливает жирное начертание шрифта.

— устанавливает курсивное начертание шрифта.

— добавляет подчеркивание к тексту.

— предназначен для акцентирования текста. Браузеры отображают такой текст курсивным начертанием.

— перечёркивает текст. Данный тег исключён из HTML5 вместо него рекомендуется использовать

— отображает текст моноширинным текстом. Исключён из HTML5.

— отображает шрифт в виде верхнего индекса. Шрифт при этом отображается выше базовой линии текста и уменьшенного размера.

— отображает шрифт в виде нижнего индекса. Текст при этом располагается ниже базовой линии остальных символов строки и уменьшенного размера.

— предназначен для акцентирования текста. Браузеры отображают такой текст жирным начертанием.

— уменьшает размер шрифта на единицу по сравнению с обычным текстом. В HTML размер шрифта измеряется в условных единицах от 1 до 7, средний размер текста, используемый по умолчанию, принят 3. Тег уменьшает текст на одну условную единицу. Допускается применение вложенных тегов , при этом размер шрифта будет меньше на 1 с каждым вложенным уровнем, но не может быть меньше, чем 1.

— увеличивает размер шрифта на единицу по сравнению с обычным текстом. В HTML размер шрифта измеряется в условных единицах от 1 до 7, средний размер текста, используемый по умолчанию, принят 3. Таким образом, добавление тега увеличивает текст на одну условную единицу. Допускается применение вложенных тегов , при этом размер шрифта будет больше с каждым уровнем.

— используется для выделения в тексте цитат. Содержимое контейнера автоматически отображается в браузере в кавычках.

— предназначен для выделения длинных цитат внутри документа. Текст, обозначенный этим тегом, традиционно отображается как выровненный блок с отступами слева и справа (примерно по 40 пикселов), а также с отбивкой сверху и снизу.

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

— определяет текстовый абзац. Тег

Является блочным элементом, всегда начинается с новой строки, абзацы текста идущие друг за другом разделяются между собой отбивкой. Величиной отбивки можно управлять с помощью стилей. Если закрывающего тега нет, считается, что конец абзаца совпадает с началом следующего блочного элемента.

.... — HTML предлагает шесть заголовков разного уровня, которые показывают относительную важность секции, расположенной после заголовка. Так, тег представляет собой наиболее важный заголовок первого уровня, а тег служит для обозначения заголовка шестого уровня и является наименее значительным. По умолчанию, заголовок первого уровня отображается самым крупным шрифтом жирного начертания, заголовки последующего уровня по размеру меньше. Теги ,…, относятся к блочным элементам, они всегда начинаются с новой строки, а после них другие элементы отображаются на следующей строке. Кроме того, перед заголовком и после него добавляется пустое пространство. Тег имеет атрибут align , который определяет выравнивание заголовка, может принимать значения left — выравнивание заголовка по левому краю, center — выравнивание по центру, right — выравнивание по правому краю, justify — выравнивание по ширине (одновременно по правому и левому краю). Это значение работает только для заголовка, длина которого более, чем одна строка.

— представляет собой контейнер для изменения характеристик шрифта, таких как размер, цвет и гарнитура. Хотя этот тег до сих пор поддерживается всеми браузерами, он считается устаревшим и от его использования рекомендуется отказаться в пользу стилей. Тег имеет 3 атрибута: color — устанавливает цвет текста, face — определяет гарнитуру шрифта, size — задает размер шрифта в условных единицах.

— помечает текст как цитату или сноску на другой материал. Такое выделение удобно для изменения стиля текста через CSS, а также применяется для разделения кода HTML на структурные элементы. Браузеры обычно устанавливают текст внутри контейнера курсивом.

— указывает, что последовательность символов является аббревиатурой. С помощью атрибута title дается расшифровка сокращения, что позволяет понимать аббревиатуру тем людям, которые с ней не знакомы. Кроме того, поисковые системы индексируют полнотекстовый вариант сокращения, что может использоваться для повышения рейтинга документа.

По умолчанию, текст заключенный в контейнере подчеркивается пунктирной линией.

Ниже приведу код, в котором я использовал все эти теги:

Мой первый сайт

HTML and CSS are two of the core technologies for building Web pages. HTML provides the structure of the page, CSS the (visual and aural) layout, for a variety of devices. Along with graphics and scripting, HTML and CSS are the basis of building Web pages and Web Applications. Learn more below about:

What is HTML?

HTML is the language for describing the structure of Web pages. HTML gives authors the means to:

Publish online documents with headings, text, tables, lists, photos, etc.
Retrieve online information via hypertext links, at the click of a button.
Design forms for conducting transactions with remote services, for use in searching for information, making reservations, ordering products, etc.
Include spread-sheets, video clips, sound clips, and other applications directly in their documents.
With HTML, authors describe the structure of pages using markup. The elements of the language label pieces of content such as “paragraph,” “list,” “table,” and so on. What is XHTML?

XHTML is a variant of HTML that uses the syntax of XML, the Extensible Markup Language. XHTML has all the same elements (for paragraphs, etc.) as the HTML variant, but the syntax is slightly different. Because XHTML is an XML application, you can use other XML tools with it (such as XSLT, a language for transforming XML content).

What is CSS?

CSS is the language for describing the presentation of Web pages, including colors, layout, and fonts. It allows to adapt the presentation to different types of devices, such as large screens, small screens, or printers. CSS is independent of HTML and can be used with any XML-based markup язык language. The separation of HTML from CSS makes it easier to maintain sites, share style sheets across pages, and tailor pages to different environments. This is referred to as the separation of structure (or: content) from presentation.

What is WebFonts? WebFonts is a technology that enables people to use fonts on demand over the Web without requiring installation in the operating system. W3C has experience in downloadable fonts through HTML, CSS2, and SVG. Until recently, downloadable fonts have not been common on the Web due to the lack of an interoperable font format. The WebFonts effort plans to address that through the creation of an industry-supported, open font format for the Web (called "WOFF").

Лекция подошла к концу, надеюсь приобретённые знания вам пригодятся! В следующей лекции я расскажу вам о том, что в себе хранит тег , научимся выполнять всевозможные манипуляции с изображениями, и познакомимся с таблицами.

При написании данной статьи описание некоторых тегов было взято отсюда

HTML (H ypert ext M arkup L anguage) is the code that is used to structure a web page and its content. For example, content could be structured within a set of paragraphs, a list of bulleted points, or using images and data tables. As the title suggests, this article will give you a basic understanding of HTML and its functions.

So what is HTML?

HTML is not a programming language; it is a markup language that defines the structure of your content. HTML consists of a series of elements , which you use to enclose, or wrap, different parts of the content to make it appear a certain way, or act a certain way. The enclosing ", and that in empty elements the end tag is neither required nor allowed. If attributes are not mentioned, default values are used in each case.">tags can make a word or image hyperlink to somewhere else, can italicize words, can make the font bigger or smaller, and so on. For example, take the following line of content:

My cat is very grumpy

If we wanted the line to stand by itself, we could specify that it is a paragraph by enclosing it in paragraph tags:

My cat is very grumpy

Anatomy of an HTML element

Let"s explore this paragraph element a bit further.

The main parts of our element are as follows:

  • The opening tag: This consists of the name of the element (in this case, p), wrapped in opening and closing angle brackets . This states where the element begins or starts to take effect - in this case where the paragraph begins.
  • The closing tag: This is the same as the opening tag, except that it includes a forward slash before the element name. This states where the element ends - in this case where the paragraph ends. Failing to add a closing tag is one of the standard beginner errors and can lead to strange results.
  • The content: This is the content of the element, which in this case, is just text.
  • The element: The opening tag, the closing tag and the content together comprise the element.
  • Elements can also have attributes that look like the following:

    Attributes contain extra information about the element that you don"t want to appear in the actual content. Here, class is the attribute name and editor-note is the attribute value . The class attribute allows you to give the element an identifier that can be used later to target the element with style information and other things.

    An attribute should always have the following:

  • A space between it and the element name (or the previous attribute, if the element already has one or more attributes).
  • The attribute name followed by an equal sign.
  • The attribute value wrapped by opening and closing quotation marks.
  • Note : Simple attribute values that don"t contain ASCII whitespace (or any of the characters " " ` = < >) can remain unquoted, but it is recommended that you quote all attribute values, as it makes the code more consistent and understandable.

    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 element, which means that the word is to be strongly emphasized:

    My cat is very grumpy.

    You do however need to make sure that your elements are properly nested. In the example above, we opened the

    element first, then the element; therefore, we have to close the element first, then the

    element. The following is incorrect:

    My cat is very grumpy.

    The elements have to open and close correctly so that they are clearly inside or outside one another. If they overlap as shown above, then your web browser will try to make the best guess at what you were trying to say, which can lead to unexpected results. So don"t do it!

    Empty elements

    Some elements have no content and are called empty elements . Take the element that we already have in our HTML page:

    This contains two attributes, but there is no closing tag and no inner content. This is because an image element doesn"t wrap content to affect it. Its purpose is to embed an image in the HTML page in the place it appears.

    Anatomy of an HTML document

    That wraps up the basics of individual HTML elements, but they aren"t handy on their own. Now we"ll look at how individual elements are combined to form an entire HTML page. Let"s revisit the code we put into our index.html example (which we first met in the Dealing with files article):

    My test page

    Here, we have the following:

    • - the doctype. It is required preamble. In the mists of time, when HTML was young (around 1991/92), 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. However these days, they don"t do much, and are basically just needed to make sure your document behaves correctly. That"s all you need to know for now.
    • - the element. This element wraps all the content on the entire page and is sometimes known as the root element.
    • - the 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.
    • - This element sets the character set your document should use to UTF-8 which includes most characters from the vast majority of 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.
    • - the element. This sets the title of your page, which is the title that appears in the browser tab the page is loaded in. It is also used to describe the page when you bookmark/favourite it.
    • - the 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.
    Images

    As we said before, it embeds an image into our page in the position it appears. It does this via the src (source) attribute, which contains the path to our image file.

    We have also included an alt (alternative) attribute. In this attribute, you specify descriptive text for users who cannot see the image, possibly because of the following reasons:

  • They are visually impaired. Users with significant visual impairments often use tools called screen readers to read out the alt text to them.
  • Something has gone wrong causing the image not to display. For example, try deliberately changing the path inside your src attribute to make it incorrect. If you save and reload the page, you should see something like this in place of the image:
  • The keywords for alt text are "descriptive text". The alt text you write should provide the reader with enough information to have a good idea of what the image conveys. In this example, our current text of "My test image" is no good at all. A much better alternative for our Firefox logo would be "The Firefox logo: a flaming fox surrounding the Earth."

    Try coming up with some better alt text for your image now.

    Marking up text

    This section will cover some of the essential HTML elements you"ll use for marking up the text.

    Headings

    Heading elements allow you to specify that certain parts of your content are headings - or subheadings. In the same way that a book has the main title, chapter titles and subtitles, an HTML document can too. HTML contains 6 heading levels, – , although you"ll commonly only use 3 to 4 at most:

    My main title My top level heading My subheading My sub-subheading

    Now try adding a suitable title to your HTML page just above your element.

    Note : You"ll see that your heading level 1 has an implicit style. Don"t use heading elements to make text bigger or bold, because they are used for accessibility and other reasons such as SEO . Try to create a meaningful sequence of headings on your pages, without skipping levels.

    Paragraphs Lists

    A lot of the web"s content is lists and HTML has special elements for these. Marking up lists always consist of at least 2 elements. The most common list types are ordered and unordered lists:

  • Unordered lists are for lists where the order of the items doesn"t matter, such as a shopping list. These are wrapped in a