Doctype
DOCTYPE. Одно название уже говорит само за себя (тип документа), но давайте копнем глубже.
Спецификация HTML 2.0 (1995 год)
To identify information as an HTML document conforming to this specification, each document must start with one of the following document type declarations.
Для определения информации о том, какой спецификации соответствует HTML документ, каждый документ должен начинаться с одного из следующий объявлений типа документа.
По сути, DOCTYPE (Document Type Declaration) определяет тип спецификации HTML. В каждой спецификации прописаны поддерживаемые ей элементы, атрибуты, и их взаимоотношения. Изначально спецификации писались в DTD, а сегодня это XML Schema.
Есть один интересный момент, в HTML коде большинства сайтов 90х годов разработчики вообще редко прописывали DOCTYPE. Потому, что браузеры тех времён могли самостоятельно выбирать спецификацию документа и поэтому у разработчиков попросту не было нужды прописывать DOCTYPE в первой строке кода.
STRAWBERRY POP-TART BLOW-TORCHES (1994) | CNN’S O.J. SIMPSON TRIAL PAGE (1996) | WELCOME TO NETSCAPE (1994) |
Но к началу нулевых годов DOCTYPE стал обязательным элементом и все веб-разработчики начали прописывать его в своих страницах. Причина кроется в том, что DOCTYPE приобрёл новое значение. Теперь он переключает режимы работы браузеров. И всё это из-за CSS!
К концу 90х годов существовало огромное количество сайтов. Веб-страницы, в основном, просматривались через такие браузеры, как Netscape Navigator и Microsoft Internet Explorer. Эти браузеры обрабатывали некоторые CSS свойства по-своему, а не в соответствии со стандартами.
Первый браузер поддерживающий CSS был Internet Explorer 3, вышедший в 1996 году. IE3 надежно поддерживал большинство цветов, фоновые и текстовые свойства, но box model (margins, paddings, borders) не была полностью реализована, а свойство display и псевдо-элементы вообще не поддерживались.
Когда было решено создать браузер полностью соответствующий стандартом CSS, оказалось, что все унаследованные страницы ломаются! Одна из главных причин была box model.
В старых версиях IE значение высоты/ширины бокса включало в себя border и padding. | Оба элемента имеют одинаковые значения высоты и ширины. Слева – стандартный; справа – старый IE. |
Поэтому в новых браузерах появились два режима обработки страниц – standart и quirk (чудачества). Страницы использующие DOCTYPE с HTML версии 4 и выше обрабатываются в соответствии со стандартами, а страницы без DOCTYPE или с DOCTYPE, но версией HTML ниже 4 обрабатываются, как в старом браузере. Даже если написать просто (без версии HTML) браузер IE6 (дата релиза: 2001 год) и выше включат стандартный режим.
Doctype html public ietf dtd html en html head
HTML is an application of ISO 8879:1986 — Standard Generalized Markup Language (SGML). SGML is a system for defining structured document types and markup languages to represent instances of those document types[SGML]. The public text — DTD and SGML declaration — of the HTML document type definition are provided in section HTML Public Text.
The term HTML refers to both the document type defined here and the markup language for representing instances of this document type.
An HTML document is an SGML document; that is, a sequence of characters organized physically into a set of entities, and logically as a hierarchy of elements.
In the SGML specification, the first production of the SGML syntax grammar separates an SGML document into three parts: an SGML declaration, a prologue, and an instance. For the purposes of this specification, the prologue is a DTD. This DTD describes another grammar: the start symbol is given in the doctype declaration, the terminals are data characters and tags, and the productions are determined by the element declarations. The instance must conform to the DTD, that is, it must be in the language defined by this grammar.
The SGML declaration determines the lexicon of the grammar. It specifies the document character set, which determines a character repertoire that contains all characters that occur in all text entities in the document, and the code positions associated with those characters.
The SGML declaration also specifies the syntax-reference character set of the document, and a few other parameters that bind the abstract syntax of SGML to a concrete syntax. This concrete syntax determines how the sequence of characters of the document is mapped to a sequence of terminals in the grammar of the prologue.
For example, consider the following document:
DTD HTML 2.0//EN">Some text. *wow*
An HTML user agent should use the SGML declaration that is given in section SGML Declaration for HTML. According to its document character set, `*’ refers to an asterisk character, `*’ .
The instance above is regarded as the following sequence of terminals:
- start-tag: TITLE
- data characters: «Parsing Example»
- end-tag: TITLE
- start-tag: P
- data characters «Some text. «
- start-tag: EM
- data characters: «*wow*»
- end-tag: EM
- end-tag: P
The start symbol of the DTD grammar is HTML, and the productions are given in the public text identified by `-//IETF//DTD HTML 2.0//EN’ (section HTML DTD). The terminals above parse as:
HTML | \-HEAD | | | \-TITLE | | | \-| | | \-"Parsing Example" | | | \- | \-BODY | \-P | \-| \-"Some text. " | \-EM | | | \- | | | \-"*wow*" | | | \- | \-
Some of the elements are delimited explicitly by tags, while the boundaries of others are inferred. The HTML element contains a HEAD element and a BODY element. The HEAD contains TITLE , which is explicitly delimited by start- and end-tags.
SGML specifies an abstract syntax and a reference concrete syntax. Aside from certain quantities and capacities (e.g. the limit on the length of a name), all HTML documents use the reference concrete syntax. In particular, all markup characters are in the repertoire of [ISO-646]. Data characters are drawn from the document character set (see section Characters, Words, and Paragraphs).
A complete discussion of SGML parsing, e.g. the mapping of a sequence of characters to a sequence of tags and data, is left to the SGML standard[SGML]. This section is only a summary.
Any sequence of characters that do not constitute markup (see 9.6 «Delimiter Recognition» of [SGML]) are mapped directly to strings of data characters. Some markup also maps to data character strings. Numeric character references map to single-character strings, via the document character set. Each reference to one of the general entities defined in the HTML DTD maps to a single-character string.
The terminating semicolon on entity or numeric character references is only necessary when the character following the reference would otherwise be recognized as part of the name (see 9.4.5 «Reference End» in [SGML]).
An ampersand is only recognized as markup when it is followed by a letter or a `#’ and a digit:
abc & lt def => "abc & lt def" abc 60 def => "abc 60 def"
A useful technique for translating plain text to HTML is to replace each » by an entity reference or numeric character reference as follows:
ENTITY NUMERIC CHARACTER REFERENCE CHAR REF CHARACTER DESCRIPTION --------- ---------- ----------- --------------------- & & & Ampersand < < < Less than >> > Greater than
Tags delimit elements such as headings, paragraphs, lists, character highlighting, and links. Most HTML elements are identified in a document as a start-tag, which gives the element name and attributes, followed by the content, followed by the end tag. Start-tags are delimited by `’ ; end tags are delimited by `' and `>‘ . An example is:
The content of an element is a sequence of data character strings and nested elements. Some elements, such as anchors, cannot be nested. Anchors and character highlighting may be put inside other constructs. See the HTML DTD, section HTML DTD for full details. (6)
A name consists of a letter followed by letters, digits, periods, or hyphens. The length of a name is limited to 72 characters by the `NAMELEN’ parameter in the SGML declaration for HTML, section SGML Declaration for HTML. Element and attribute names are not case sensitive, but entity names are. For example, `’ , `’ , and `’ are equivalent, whereas `&’ is different from `&’ .
In a start-tag, the element name must immediately follow the tag open delimiter `
In a start-tag, white space and attributes are allowed between the element name and the closing delimiter. An attribute specification typically consists of an attribute name, an equal sign, and a value, though some attribute specifications may be just a name token. White space is allowed around the equal sign.
The value of the attribute may be either:
- A string literal, delimited by single quotes or double quotes and not containing any occurrences of the delimiting character. (7)
- A name token (a sequence of letters, digits, periods, or hyphens). Name tokens are not case sensitive. (8)
In this example, img is the element name, src is the attribute name, and `http://host/dir/file.gif’ is the attribute value:
A useful technique for computing an attribute value literal for a given string is to replace each quote and white space character by an entity reference or numeric character reference as follows:
ENTITY NUMERIC CHARACTER REFERENCE CHAR REF CHARACTER DESCRIPTION --------- ---------- ----------- --------------------- HT Tab LF Line Feed CR Carriage Return SP Space " " " Quotation mark & & & Ampersand
The `NAMELEN’ parameter in the SGML declaration (section SGML Declaration for HTML) limits the length of an attribute value to 1024 characters.
Attributes such as ISMAP and COMPACT may be written using a minimized syntax (see 7.9.1.2 «Omitted Attribute Name» in [SGML]). The markup:
can be written using a minimized syntax:
To include comments in an HTML document, use a comment declaration. A comment declaration consists of `’ . Each comment starts with `—‘ and includes all text up to and including the next occurrence of `—‘ . In a comment declaration, white space is allowed after each comment, but not before the first comment. The entire comment declaration is ignored. (10)
DTD HTML 2.0//EN»>
To identify information as an HTML document conforming to this specification, each document must start with one of the following document type declarations.
This document type declaration refers to the HTML DTD in section HTML DTD. (11)
This document type declaration also refers to the HTML DTD which appears in section HTML DTD.
This document type declaration refers to the level 1 HTML DTD in section Level 1 HTML DTD. Form elements must not occur in level 1 documents.
DTD HTML 2.0 Strict//EN"> DTD HTML 2.0 Strict Level 1//EN">
These two document type declarations refer to the HTML DTD in section Strict HTML DTD and section Strict Level 1 HTML DTD. They refer to the more structurally rigid definition of HTML.
HTML user agents may support other document types. In particular, they may support other formal public identifiers, or other document types altogether. They may support an internal declaration subset with supplemental entity, element, and other markup declarations.