Code tag use in html

Code tag use in html

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

const greeting = 'Привет, мир!'; 

Примеры использования

Приведём фрагмент кода:

function sum(a, b)

Вы можете объявить переменные с помощью ключевых слов var, let или const.

Используйте <br> тег, чтобы добавить перенос строки.

НажмитеCtrl+C, чтобы скопировать.

Используйте<code> тег, чтобы отобразить код.

Зайдите на сайт https://example.com.

Для чего использовать тег

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

Глобальные атрибуты

Ограничения

Элемент не следует использовать для форматирования текста типографским способом. Тег предназначен для отображения компьютерного кода, а не для обычного текста. Кроме того, не нужно использовать для синтаксиса разметки — вместо него следует использовать элемент .

Нюансы

  • Если содержит HTML-элементы < , >или & , то их нужно экранировать с помощью < , > или & .
  • Если тег используется для отображения кода с отступом, то пробелы или табуляции, используемые для отступа, могут привести к тому, что код переместится на следующую строку (если элемент контейнера недостаточно широк).

Чем заменить тег

Чтобы отобразить программный код, используйте тег . Однако, если вам нужно отобразить синтаксис разметки или текст, который должен отображаться с форматированием фиксированной ширины, используйте тег .

🔡 Другие теги для изменения текста

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

Источник

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

code exemple

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.

Источник

Code tag use in html

Тег для оформления программного кода.

Время чтения: меньше 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')      

Источник

Читайте также:  Php действие после нажатия кнопки
Оцените статью