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:
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 существует два типа элементов - блочные (block elements) и строчные (inline elements). Ниже вы узнаете особенности этих элементов и разницу между ними, а также способы управлять ими через правила CSS.
Блочные элементы
Блочные элементы являются основой, которая используется для верстки веб-страниц. Такой элемент представляет собой прямоугольник, который по умолчанию занимает всю доступную ширину страницы (если иное значение не указано в CSS), а длина элемента зависит от его содержимого. Такой элемент всегда начинается с новой строки, то есть, располагается под предыдущим элементом. Блочный элемент может содержать в себе другие блочные и строчные элементы.
Примеры блочных элементов:
,
- ,
- Внутрь строчно-блочных элементов допустимо помещать текст, строчные или блочные элементы.
- Высота элемента вычисляется браузером автоматически, исходя из содержимого блока.
- Ширина равна содержимому плюс значения отступов, полей и границ.
- Несколько элементов идущих подряд располагаются на одной строке и переносятся на другую строку при необходимости.
- Можно выравнивать по вертикали с помощью свойства vertical-align .
- Разрешено задавать ширину и высоту.
- Эффект схлопывания отступов не действует.
- ,
и т. д.
Строчные элементы
В отличие от блочного, строчный элемент не переносится на новую строку, а располагается на той же строке, что и предыдущий элемент. Такие элементы, как правило, находятся внутри блочных элементов и их ширина зависит лишь от содержимого и настроек CSS. Еще одно отличие строчного элемента от блочного заключается к том, что в нем может находиться только контент и другие строчные элементы. Блочные элементы в строчные вкладывать нельзя.
Примеры строчных элементов:
, , , , и т. д.
Примечание: в HTML5 порядок вложения тегов такой роли не играет. Элементы уже не просто делятся на блочные и строчные, а группируются по смыслу и назначению, представляя собой категории контента .
CSS-свойство display: меняем тип элемента
При помощи крайне полезного свойства display в CSS можно заставить блочный элемент выглядеть как строчный и наоборот. Чтобы блочный элемент вел себя как inline-элемент (т. е. не переводился на новую строку), для него необходимо записать правило:
Display: inline;
Если же необходимо отобразить строчный элемент как block-элемент (чтобы до и после элемента происходил перенос строки), запишите следующее:
Display: block;
Действие {display:inline} и {display:block}
Также можно сделать «гибрид» - блочный элемент с поведением, как у строчного. В этом случае всё содержимое таких блочных элементов будет отображаться, как обычно, но при этом блоки будут вести себя как строчные элементы, выстраиваясь в одной строке друг за другом и переносясь на новую строку лишь при необходимости. Схлопывание margin в таких случаях перестает действовать. Для превращения элемента в блочно-строчный запишите:
Display: inline-block;
Действие {display:inline-block}
Далее в учебнике: свойство CSS border . Вы узнаете, как добавлять границы для элементов веб-страницы и какие настройки к ним можно применить, используя каскадные таблицы стилей.
Блочные и строчные элементы отлично дополняют друг друга при вёрстке, занимая каждый свою определённую нишу. Но возникают случаи, когда характеристик этих элементов явно недостаточно. Галерея фотографий, представленная на рис. 3.28 состоит из секций, в которые входит изображение с подписью к нему, при этом секции выстраиваются по горизонтали, занимая всю доступную ширину. При уменьшении окна браузера секции переходят на другую строку.
Рис. 3.28. Галерея фотографий
Если для формирования секций использовать тег
В HTML нет тега, который относится к строчно-блочным элементам, его можно определить, задав элементу свойство display со значением inline-block .
Div { display: inline-block; }
Характеристики этих элементов следующие.
Чтобы создать галерею, представленную на рис. 3.28 для тега
(пример 3.18).
Пример 3.18. Использование display
XHTML 1.0 CSS 2.1 IE 7 IE 8+ Cr Op Sa Fx
Поскольку все фотографии имеют одинаковый размер, ширина блока задана явно и равна 150px, но высота не указывается, поэтому при длинной подписи к рисунку высота секций будет различаться (рис. 3.29).
Рис. 3.29. Разная высота секций
Это не является проблемой, поскольку в любом случае секции будут выводиться упорядоченно рядами, несмотря на разную высоту. При этом можно изменить вид выравнивания через vertical-align , добавив это свойство к классу photo . Если указать значение top , то поменяется отображение секций (рис. 3.30).
Рис. 3.30. Выравнивание по верхнему краю
Основной проблемой выступает браузер IE до версии 7.0 включительно. Этот браузер применяет значение inline-block только для строчных элементов и с блочными элементами работает некорректно. Чтобы убедить этот браузер правильно отображать наш пример, необходимо вместо inline-block использовать значение inline и установить свойство hasLayout . Добавление inline разрушит макет в остальных браузерах, поэтому правильным решением будет воспользоваться условными комментариями (пример 3.19).
Пример 3.19. Стиль для IE
Конструкция означает применить указанный код для браузера IE версии 7.0 и ниже. Остальные браузеры воспринимают её как комментарий и игнорируют. Что касается свойства zoom , оно нестандартное и предназначено для установки свойства hasLayout , напрямую которое задавать нельзя.
Также строчно-блочные элементы удобно использовать для различных каталогов товаров, которые встречаются в интернет-магазинах. Обычно они выводятся с картинкой и подписью к ней. Всё это похоже на галерею, сделанную выше, поэтому остаётся только модифицировать её код, учесть выравнивание по высоте и поведение IE (пример 3.20).
Пример 3.20. Каталог товаров
XHTML 1.0 CSS 2.1 IE Cr Op Sa Fx
Видео 1856
Фото 315
Мобильные устройства 2109
Компьютеры и орг.техника 4296
Бытовая техника 731
Результат данного примера показан на рис. 3.31.
Рис. 3.31. Каталог товаров
Чтобы не задавать каждому тегу
Элементы HTML по способу отображения на веб-странице делятся на строчные и блочные элементы.
Строчные элементы (inline)
Строчные элементы предназначены для выполнения некоторых действий над текстом, например: перенос строки, выделения фрагмента текста курсивом, логического выделения некоторого текста и применения к нему стилей с помощью CSS и т.д. В зависимости от назначения строчного элемента фрагмент текста помещают между открывающим и закрывающим тегом или применяют тег в любом месте текста, например для переноса строки.
Например:
Можно использовать строчный элемент чтобы выделить текст, привлекающий внимание посетителей сайта с помощью жирного начертания.
Строчный элемент имеет ширину, которая равна ширине его содержимого. Строчные элементы не могут содержать внутри себя блочные элементы.
Примеры строчных элементов: , ,