Блочные элементы html. Блочные и встроенные элементы. Блочные и внутристрочные теги
В HTML большинство элементов можно разделить на две группы: блочные (blok ) и строчные (inline ).
Начинающему разработчику не всегда сразу удается разобраться - в чем разница между ними, а также запомнить принадлежность какого-либо элемента к конкретной группе. Но со временем, с опытом работы у Вас не возникнет и намека на подобные затруднения.
Строчные элементы
К строчным элементам относятся теги:
,
,
,
,
, ,
,
,
....
Строчные элементы в общем потоке располагаются последовательно на одной строке один за другим.
На другую строку строчный элемент или часть его содержимого переходит только в конце строки или когда что-то принудительно заставляет их перейти на новую строку.
Строчные элементы, естественно, могут располагаться внутри блочных.
Блочные элементы
К блочным элементам относятся теги:
-
,
- Block-level elements may appear only within a element.
...
,
,
,
,
,
....
Блок представляет собой как бы отдельную структурную единицу, выделенную абзацем. Блочные элементы в общем потоке располагаются последовательно один под другим
. По умолчанию два блочных элемента не могут располагаться на одной строке.
Один или несколько блоков также могут располагаться внутри другого (родительского
) блочного элемента.
В CSS блоки создаются на основе элементов HTML и имеют следующую структуру.
Любой блок имеет форму прямоугольника.
Блочный элемент имеет границу и содержимое: это может быть текстовая информация, фотографии, логотип фирмы и т.п., называемое контентом (англ. content
- содержание
).
Границе блока при помощи свойства border
можно придать необходимое оформление: задать толщину, цвет и стиль линий. По умолчанию граница невидима.
Между содержимым и границей существуют внутренние расстояния - поля
(свойство padding
). Ими необязательно пользоваться. То есть если их явно не установить при помощи свойства padding
, то граница будет вплотную примыкать к содержимому блока, либо отстоять от него на каком-то минимальном расстоянии. С другой стороны, поля могут иметь совершенно конкретные размеры, которые указывает разработчик.
Вокруг блока - за его границей существуют пустые, ничем не занятые области, называемые отступами
(свойство margin
). Отступы - это расстояния от границы блока, до ближайших элементов, или, если их нет, то до краев окна браузера. Отступы также, как и поля по умолчанию отсутствуют, либо имеют минимальную ширину, автоматически определяемую браузером.
Также для блока можно задать фиксированную ширину (свойство width
) и высоту (свойство height
), но лишь для его содержимого. Отступы, граница и поля туда не входят. По умолчанию как высота, так и ширина блока подстраиваются под размеры пространства, занимаемого контентом.
Фрагмент кода:
Строчные элементы
расположены на одной строке.
Они заключены в блочный элемент - абзац!
Перенос текста происходит автоматически - в конце строки.
Следующий блок - абзац, начинается с новой строки.
Два абзаца расположены.
Внутри блока - тега
div
!
Отдельные фрагменты текста заключены в тег span. И для них задано стилевое оформление!
Результат:
Строчные элементы расположены на одной строке.
Они заключены в блочный элемент - абзац!
Перенос текста происходит автоматически - в конце строки.
Следующий блок - абзац, начинается с новой строки.
Два абзаца расположены.
Внутри блока - тега div
!
Отдельные фрагменты текста заключены в тег span. И для них задано стилевое оформление!
HTML (Hypertext Markup Language
) elements historically were categorized as either "block-level" elements or "inline" elements. Inline elements are those which only occupy the space bounded by the tags defining the element, instead of breaking the flow of the content.
In this article, we"ll examine HTML inline elements and how they differ from block-level elements .
An inline element does not start on a new line and only takes up as much width as necessary.
Inline vs. block-level elements: a demonstration
This is most easily demonstrated with a simple example. First, some simple CSS that we"ll be using:
Highlight {
background-color:#ee3;
}
Inline
Let"s look at the following example which demonstrates an inline element:
The following span is an inline element;
its background has been colored to display both the beginning and end of
the inline element"s influence.
The following paragraph is a block-level element;
its background has been colored to display both the beginning and end of
the block-level element"s influence.
The CSS (not displayed in standard reading mode) is also used:
Body {
margin: 0;
padding: 4px;
border: 1px solid #333;
}
.highlight {
background-color:#ee3;
}
Rendered using the same CSS as before, we get:
See the difference? The
Element totally changes the layout of the text, splitting it into three segments: the text before the
Then the
"s text, and finally the text following the
Changing element levels
You can change the visual presentation
of an element using the CSS display property. For example, by changing the value of display from "inline" to "block" , you can tell the browser to render the inline element in a block box rather than an inline box, and vice versa. However, doing this will not change the category
and the content model
of the element. For example, even if the display of the span element is changed to "block" , it still would not allow to nest a div element inside it.
Conceptual differences
In brief, here are the basic conceptual differences between inline and block-level elements:
Content model
Generally, inline elements may contain only data and other inline elements. You can"t put block elements inside inline elements.
Formatting
By default, inline elements do not force a new line to begin in the document flow. Block elements, on the other hand, typically cause a line break to occur (although, as usual, this can be changed using CSS).
List of "inline" elements
The following elements are inline by default (although block and inline elements are no longer defined in HTML 5, use
HTML (Hypertext Markup Language
) elements historically were categorized as either "block-level" elements or "inline" elements . By default, a block-level element occupies the entire space of its parent element (container), thereby creating a "block." This article helps to explain what this means.
Browsers typically display the block-level element with a newline both before and after the element. You can visualize them as a stack of boxes.
A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
The following example demonstrates the block-level element"s influence:
Block-level elements
HTML
This paragraph is a block-level element; its background has been colored to display the paragraph"s parent element.
CSS
p { background-color: #8ABB55; }
Usage
Block-level vs. inline
There are a couple of key differences between block-level elements and inline elements:
Content model
Generally, block-level elements may contain inline elements and (sometimes) other block-level elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.
Default formatting
By default, block-level elements begin on new lines, but inline elements can start anywhere in a line.
Elements
The following is a complete list of all HTML "block-level" elements (although "block-level" is not technically defined for elements that are new in HTML5).
Contact information.
Article content.
element represents a portion of a document whose content is only indirectly related to the document" s main content.>
Aside content.
Element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation (see Notes for how to change it). A URL for the source of the quotation may be given using the cite attribute, while a text representation of the source can be given using the element.">
Long ("block") quotation.
Disclosure widget.
element represents a dialog box or other interactive component, such as an inspector or window.">
,
-
,
,