Блочные и строчные элементы. Блочные и встроенные элементы

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

Строчными называются такие элементы документа, которые являются непосредственной частью строки. К строчным элементам относятся теги , , , , и др., а также элементы, у которых свойство display установлено как inline . В основном они используются для изменения вида текста или его логического выделения.

По аналогии с блочными элементами перечислю их характерные особенности.

  • Внутрь строчных элементов допустимо помещать текст или другие строчные элементы. Вставлять блочные элементы внутрь строчных запрещено.
  • Эффект схлопывания отступов не действует.
  • Свойства, связанные с размерами (width , height ) не применимы.
  • Ширина равна содержимому плюс значения отступов, полей и границ.
  • Несколько строчных элементов идущих подряд располагаются на одной строке и переносятся на другую строку при необходимости.
  • Можно выравнивать по вертикали с помощью свойства vertical-align .

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

Для вёрстки строчные элементы применяются реже, чем блочные. Это связано в основном с тем, что внутрь строчных элементов не допускается вкладывать контейнеры

,

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

Пример 3.16. Применение тега

Строчные элементы

Лягте животом на пол. Соедините стопы вместе, согнув ноги в коленях и развернув их в стороны. Руки за головой. Тяните голову руками вверх и вперед до полного сокращения мышц живота. Задержитесь на две секунды. Выполните восемь повторений.

Результат примера показан ниже (рис. 3.25).

Рис. 3.25. Текст, оформленный с помощью стилей

В данном примере тег и стили используются для выделения различными способами фрагментов текста. В частности, выделение происходит за счёт фонового цвета, рамки вокруг текста и сменой его цвета. Обратите внимание, что в результате переноса текста рамка вокруг него также перенеслась на другую строку. Во многих случаях это выглядит не очень красиво, поэтому можно запретить перенос текста через white-space : nowrap .

Для текста, который не обрамлён строчным тегом вроде создаётся анонимный строчный элемент. Для примера выше схема элементов будет следующей (рис. 3.26).

Рис. 3.26. Анонимные строчные элементы

Серым цветом на рисунке помечен текст внутри тега , а пунктиром анонимные строчные элементы. Для таких элементов задать стиль напрямую нельзя, он наследуется от родителя.

Преобразование в строчный элемент

Строчные элементы можно превращать в блочные с помощью свойства display и его значения block . Также возможно и обратное действие через значение inline (пример 3.17).

Пример 3.17. Свойство display

XHTML 1.0 CSS 2.1 IE Cr Op Sa Fx

Строчные элементы

Примечание

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

Результат примера приведен на рис. 3.27.

Рис. 3.27. Замена блочного элемента на строчный

В данном примере блочный тег

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

В виде строчного элемента. В принципе, аналогичным решением будет использовать вместо

Тег .

Учтите, что преобразование элемента в строчный не даёт право нарушать последовательность вложения тегов и вкладывать блочные элементы внутрь строчных.

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 elements may appear only within a element.

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."> Dialog box. element provides the details about or the definition of the preceding term (
) in a description list (
).">
Describes a term in a description list. ) is the generic container for flow content. It has no effect on the content or layout until styled using CSS.">
Document division. element represents a description list. The element encloses a list of groups of terms (specified using the
element) and descriptions (provided by
elements). Common uses for this element are to implement a glossary or to display metadata (a list of key-value pairs).">
Description list. element specifies a term in a description or definition list, and as such must be used inside a
element.">
Description list term. element is used to group several controls as well as labels (
Field set label.
element, if any.">
Figure caption. element represents self-contained content, frequently with a caption (
), and is typically referenced as a single unit.">
Groups media content with a caption (see element represents a caption or legend for the rest of the contents its parent
element, if any.">
). element represents a footer for its nearest sectioning content or sectioning root element. A footer typically contains information about the author of the section, copyright data or links to related documents.">