- HTML Computer Code Elements
- Example
- HTML For Keyboard Input
- Example
- HTML For Program Output
- Example
- HTML For Computer Code
- Example
- Example
- HTML For Variables
- Example
- Chapter Summary
- HTML Exercises
- HTML Computer Code Elements
- HTML Tag
- Syntax
- Example of the HTML tag:
- Result
- Example of the HTML tag placed inside an HTML tag:
- Example of the HTML tag with CSS properties:
- Attributes
- How to style tag?
- Common properties to alter the visual weight/emphasis/size of text in tag:
- Coloring text in tag:
- Text layout styles for tag:
- Other properties worth looking at for tag:
- : The Inline Code element
- Try it
- Attributes
- Examples
- Result
- Notes
- Technical summary
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Html tag for programming code
- Кратко
- Как пишется
- Как понять
- Подсветка синтаксиса
- HTML Программный код
HTML Computer Code Elements
HTML contains several elements for defining user input and computer code.
Example
HTML For Keyboard Input
The HTML element is used to define keyboard input. The content inside is displayed in the browser’s default monospace font.
Example
Define some text as keyboard input in a document:
Save the document by pressing Ctrl + S
HTML For Program Output
The HTML element is used to define sample output from a computer program. The content inside is displayed in the browser’s default monospace font.
Example
Define some text as sample output from a computer program in a document:
Message from my computer:
File not found.
Press F1 to continue
File not found.
Press F1 to continue
HTML For Computer Code
The HTML element is used to define a piece of computer code. The content inside is displayed in the browser’s default monospace font.
Example
Define some text as computer code in a document:
Notice that the element does not preserve extra whitespace and line-breaks.
To fix this, you can put the element inside a element:
Example
HTML For Variables
The HTML element is used to define a variable in programming or in a mathematical expression. The content inside is typically displayed in italic.
Example
Define some text as variables in a document:
The area of a triangle is: 1/2 x b x h, where b is the base, and h is the vertical height.
Chapter Summary
- The element defines keyboard input
- The element defines sample output from a computer program
- The element defines a piece of computer code
- The element defines a variable in programming or in a mathematical expression
- The element defines preformatted text
HTML Exercises
HTML Computer Code Elements
Tag | Description |
---|---|
Defines programming code | |
Defines keyboard input | |
Defines computer output | |
Defines a variable | |
Defines preformatted text |
For a complete list of all available HTML tags, visit our HTML Tag Reference.
HTML Tag
The tag is used to insert variables, fragments of program code, etc. into an HTML document. In the browser, the code is displayed in a monospaced font (a font in which all characters have the same width) of the smaller size.
The tag alone represents a single code line or code phrase. It should be wrapped within a element for representing several lines of code.
You can use CSS to achieve better effects.
Syntax
The tag comes in pairs. The content is written between the opening (
) and closing (
) tags.
Example of the HTML tag:
html> html> head> title>Title of the document title> head> body> p>Ordinary text. p> code>Line of program code. code> p>Continuation of the ordinary text. p> body> html>
Result
Example of the HTML tag placed inside an HTML tag:
html> html> head> title>Title of the document title> head> body> pre> code> body < color: yellow; font-size: 16px; line-height: 1.5; >code> pre> body> html>
Example of the HTML tag with CSS properties:
html> html> head> title>Title of the document title> style> .code-style < font-size: 20px; line-height: 28px; background-color: lightblue; color: #ffffff; > style> head> body> p>Ordinary text. p> code class="code-style">Line of program code. code> p>Continuation of the ordinary text. p> body> html>
Attributes
How to style tag?
Common properties to alter the visual weight/emphasis/size of text in tag:
- CSS font-style property sets the style of the font. normal | italic | oblique | initial | inherit.
- CSS font-family property specifies a prioritized list of one or more font family names and/or generic family names for the selected element.
- CSS font-size property sets the size of the font.
- CSS font-weight property defines whether the font should be bold or thick.
- CSS text-transform property controls text case and capitalization.
- CSS text-decoration property specifies the decoration added to text, and is a shorthand property for text-decoration-line, text-decoration-color, text-decoration-style.
Coloring text in tag:
- CSS color property describes the color of the text content and text decorations.
- CSS background-color property sets the background color of an element.
Text layout styles for tag:
- CSS text-indent property specifies the indentation of the first line in a text block.
- CSS text-overflow property specifies how overflowed content that is not displayed should be signalled to the user.
- CSS white-space property specifies how white-space inside an element is handled.
- CSS word-break property specifies where the lines should be broken.
Other properties worth looking at for tag:
- CSS text-shadow property adds shadow to text.
- CSS text-align-last property sets the alignment of the last line of the text.
- CSS line-height property specifies the height of a line.
- CSS letter-spacing property defines the spaces between letters/characters in a text.
- CSS word-spacing property sets the spacing between words.
: The Inline Code element
The HTML element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code. By default, the content text is displayed using the user agent's default monospace font.
Try it
Attributes
This element only includes the global attributes.
Examples
A paragraph of text that includes :
p> The function code>selectAll()code> highlights all the text in the input field so the user can, for example, copy or delete the text. p>
Result
Notes
A CSS rule can be defined for the code selector to override the browser's default font face. Preferences set by the user might take precedence over the specified CSS.
Technical summary
Content categories | Flow content, phrasing content, palpable content. |
---|---|
Permitted content | Phrasing content. |
Tag omission | None, both the starting and ending tag are mandatory. |
Permitted parents | Any element that accepts phrasing content. |
Implicit ARIA role | No corresponding role |
Permitted ARIA roles | Any |
DOM interface | HTMLElement Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the HTMLSpanElement interface for this element. |
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 13, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Html tag for programming code
Тег для оформления программного кода.
Время чтения: меньше 5 мин
Обновлено 7 сентября 2022
Кратко
Скопировать ссылку "Кратко" Скопировано
Тег используется для вывода фрагментов программного кода.
Как пишется
Скопировать ссылку "Как пишется" Скопировано
const element = document.getElementById('#some-id');
code> const element = document.getElementById('#some-id'); code>
Как понять
Скопировать ссылку "Как понять" Скопировано
используется для вывода любой информации, которая может быть обработана компьютером как программный код. Помимо непосредственно кода, сюда также относятся названия файлов, конфигурационные файлы, XML-элементы и т. д.
Тег по умолчанию строчный и браузеры не применяют к тексту внутри него никакого форматирования, кроме font - family : monospace; , и не подсвечивают синтаксис. Они не анализируют содержимое и не делают никаких предположений, на каком языке программирования написан вставленный код.
Изначально предназначен для вывода информации во фразовом контексте. Например, мы можем вставить код в середину предложения.
Пожалуй,
i
— самое часто встречающееся имя переменной.p>Пожалуй, code>icode> — самое часто встречающееся имя переменной.p>
Если мы хотим вывести блок кода, то нужно дополнительно использовать тег для вывода кода с сохранением форматирования.
for(let i = 0; i < 10; i++) console.log(i) >
pre>code> for(let i = 0; i < 10; i++)< console.log(i) >code>pre>
Подсветка синтаксиса
Скопировать ссылку "Подсветка синтаксиса" Скопировано
Если мы хотим красивого форматирования и подсветки синтаксиса, мы должны использовать сторонние инструменты и дополнительно пометить код, например, при помощи атрибута class . Для этого обычно используются библиотеки, такие как highlight.js и prism.js.
Например, они генерируют HTML приблизительно такого вида:
const element = document . getElementById ( '#some-id' )
pre class="block-code font-theme font-theme--code" data-lang="html"> code class="block-code__highlight"> span class="token keyword">constspan> element span class="token operator">=span> span class="token dom variable">documentspan> span class="token punctuation">.span> span class="token method function property-access">getElementByIdspan> span class="token punctuation">(span> span class="token string">'#some-id'span> span class="token punctuation">)span> code> pre>
А пользователи его увидят вот так:
const element = document.getElementById('#some-id')
const element = document.getElementById('#some-id')
HTML Программный код
Надписи, выполненные моноширинными шрифтами, создаются с помощью тегов , и . Результаты применения этих тегов обычно идентичны: моноширинный шрифт с фиксированным размером символов и интервалов.
Тег
Тег — cтрочный элемент-контейнер, который применяется для вставки в него небольших фрагментов программного кода, например, в веб-документе, представляющем учебное пособие по программированию. Браузеры отображают такой код моноширинным шрифтом (например, Courier New). Если использовать ero совместно с элементом , то можно сохранить исходное форматирование кода.
Тег служит для ввода текста без форматирования, то есть с сохранением всех пробелов, табуляций и переносов строк. Внутри этого элемента можно применять большинство элементов форматирования текста.
Внимание: В языке HTML переносы строк, идущие подряд пробелы и табуляции игнорируются. Несколько пробелов подряд воспринимаются как один пробел.
Пример: использования элементов и
Внутри элемента браузер дублирует каждый встреченный пробел или перенос строки, сохраняя ваше исходное форматирование.
if (document.getElementsByClassName) < x = document.getElementsByClassName("pagination") if ( x.length>y)Внутри элемента «pre» браузер дублирует каждый встреченный пробел или перенос строки, сохраняя ваше исходное форматирование.
if (document.getElementsByClassName) < x = document.getElementsByClassName("pagination") if ( x.length>y)
Теги иТег отмечает фрагмент кода как вводимый пользователем с клавиатуры. Некоторые браузеры помечают такой текст дополнительным фоном.
Тег применяется для формирования компьютерного вывода, например, текста, отображаемого в консольном окне после ввода вами управляющего сценария. Этот редко используемый элемент просто выводит свое содержимое моноширинным шрифтом, как , , .Пример: элементы и
Текст, который пользователь должен ввести с клавиатуры поместите
в элемент-контейнер «kbd».Введите текст: Это — текст, вводимый с клавиатуры
Это — текст, который помещен в контейнер «samp»
Текст, который пользователь должен ввести с клавиатуры поместите в
элемент-контейнер «kbd».Введите текст: Это — текст, вводимый с клавиатуры
Это — текст, который помещен в контейнер «samp»
Тег
Тег используется с целью дополнительного выделения переменных в программном коде. Он определяет переменную в математическом выражении или параметр программы и обычно отображается курсивом.
Пример: элементы
Кинетическая энергия тела: