What is html code element

: 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

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.

Attributes

This element only includes the global attributes.

Example

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>

The output generated by this HTML looks like this:

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.

Читайте также:  Style text color in javascript

Specifications

Источник

: 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 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.

Источник

What is html code element

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

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

Источник

code element

If you don’t know what an element is or how you must use it, I recommend you read the » HTML tags and attributes» tutorial that you can find in the HTML tutorials section.

Description

The code element represents a fragment of computer code, which can be any piece of computer readable text. Among many other examples, you can find inside the code element, a piece of a program in any programming language, an HTML or XML document, a set of CSS declarations, the contents of a configuration file, etc.

The code element is usually placed inside pre to take advantage of its characteristics: spaces and line breaks in the code are respected and rendered in the document.

Examples

Our first example shows a basic inline usage of the code element.

  You should declare the function as follows: function changeColor(element, event) , where the content of the function is represented by the ellipsis.  

You should declare the function as follows: function changeColor(element, event) < . >, where the content of the function is represented by the ellipsis.

The second example contains a piece of text in which a full Javascript function is shown. The function is properly wrapped with the code element, which provides semantic information about what it represents (computer code).

Additionally, the function code is also wrapped with the pre element to include the benefits of this element when writting the function: the spaces and line breaks in the code will be respected and rendered in the document. Using these two elements together is a very common practice when creating documents with code fragments.

  . and this is the function that changes the color of the element or its parent when the event is fired:    function changeColor(element, event)   if (typeof event != 'undefined') event.preventDefault();  if (typeof $(element).data('transparentBackground') == 'undefined' || $(element).data('transparentBackground'))   $(element).css();  $(element).data('transparentBackground', 0);  > else   $(element).css();  $(element).data('transparentBackground', 1);  > >  

. and this is the function that changes the color of the element or its parent when the event is fired:

function changeColor(element, event) < if (typeof event != 'undefined') event.preventDefault(); if (typeof $(element).data('transparentBackground') == 'undefined' || $(element).data('transparentBackground')) < $(element).css(); $(element).data('transparentBackground', 0); > else < $(element).css(); $(element).data('transparentBackground', 1); > > 

Note how the code element is contained by the pre element. This is because the first one is a phrasing element (formerly inline) and can’t contain flow elements (previously block-level) like pre .

Attributes

Global attributes

For information about global attributes refer to this list of global attributes in HTML 5.

Events

Global events

For information about global events refer to this list of global events in HTML 5.

Tutorials

Reference

Источник

Оцените статью