Что такое атрибут в html
Перейти к содержимому

Что такое атрибут в html

  • автор:

HTML Атрибуты

Атрибуты предоставляют дополнительную информацию об элементах HTML.

HTML Атрибуты

  • Все элементы HTML могут иметь атрибуты
  • Атрибуты предоставляют дополнительную информацию об элементе
  • Атрибуты всегда указываются в начальном теге
  • Атрибуты обычно входят в пары имя/значение, например: имя="значение"

Атрибут href

HTML ссылки определяются с помощью тега <a> . Адрес ссылки указывается в атрибуте href :

Пример

Подробнее о ссылках и теге <a> можно узнать в следующих разделах этого учебника.

Атрибут src

HTML изображения определяются с помощью тега <img> .

Имя файла источника изображения указывается в атрибуте src :

Пример

Атрибуты width (ширина) и height (высота)

HTML изображения также имеют атрибуты width (ширина) и height (высота), которые определяют ширину и высоту изображения:

Пример

Ширина и высота указываются в пикселях по умолчанию; поэтому width="500" означает ширину 500 пикселей.

Подробнее об изображениях вы узнаете в главе HTML Изображения.

Атрибут alt

Атрибут alt указывает альтернативный текст, который будет использоваться, если изображение не может быть отображено.

Значение атрибута alt может быть прочитано программами чтения с экрана (скринридерами). Таким образом, можно "прослушивать" веб-страницы, например, человек с нарушениями зрения может "слышать" элемент, т.е. будет знать, что изображено на картинке.

Пример

Атрибут alt также полезен, если изображение не может быть отображено (например, если оно не существует на сайте):

Пример

Посмотрите, что произойдет, если мы попытаемся отобразить изображение, которое не существует:

Атрибут style

Атрибут style используется для указания стиля элемента, такого как цвет, шрифт, размер и т.д.

Пример

Вы узнаете больше о стилизации позже в этом учебнике, и в CSS Учебнике на этом сайте.

Атрибут lang

Язык документа может быть объявлен в теге <html> .

Язык объявляется с помощью атрибута lang .

Объявление языка важно для приложений с расширенными возможностями (средства чтения с экрана) и поисковых систем:

Первые две буквы указывают на язык (en). Если есть диалект, добавьте еще две буквы (US, т.е. США).

Атрибут title

Здесь атрибут title добавляется к элементу <p> . Значение атрибута title будет отображаться в виде всплывающей подсказки при наведении мыши на абзац (параграф):

Пример

Использовать строчные атрибуты (в нижнем регистре)

Стандарт HTML5 не требует строчных имен атрибутов.

Атрибут title может быть написан в верхнем или нижнем регистре, например title или TITLE.

W3C рекомендует использовать нижний регистр в HTML и требует нижний регистр для более строгих типов документов, таких как XHTML.

В W3Schools всегда используют имена атрибутов в нижнем регистре.

Мы предлагаем: значения атрибутов брать в кавычки

Стандарт HTML5 не требует кавычек вокруг значений атрибутов.

Значение атрибута href , показанного выше, можно писать без кавычек:

Плохо

Хорошо

W3C рекомендует кавычки в HTML и требует кавычки для более строгих типов документов, например XHTML.

Иногда необходимо использовать кавычки. Этот пример не будет правильно отображать атрибут title, поскольку он содержит пробел:

Пример

Использование кавычек является наиболее распространенным при написании HTML-кода. Пропуск кавычек может привести к ошибкам. В W3Schools всегда используют кавычки вокруг значений атрибутов.

Одинарные или двойные кавычки?

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

В некоторых ситуациях, когда само значение атрибута содержит двойные кавычки, необходимо использовать одинарные кавычки:

Резюме раздела

  • Все HTML элементы могут иметь атрибуты
  • Атрибут title обеспечивает дополнительную информацию в виде "всплывающей подсказки"
  • Атрибут href предоставляет адресную информацию для ссылок
  • Атрибуты width и height предоставляют информацию о размере изображений
  • Атрибут alt предоставляет текст для программ чтения с экрана
  • В W3Schools всегда используют строчные (в нижнем регистре) значения атрибутов
  • В W3Schools всегда значения атрибутов в кавычках

HTML Упражнения

HTML Атрибуты

Ниже приведен алфавитный список некоторых атрибутов, часто используемых в HTML, о которых вы узнаете больше в этом учебнике:

Атрибут Описание
alt Определяет альтернативный текст для изображения, когда изображение не может быть отображено
disabled Указывает, что входной элемент должен быть отключен
href Указывает URL-адрес (веб-адрес) для ссылки
id Указывает уникальный идентификатор элемента
src Указывает URL-адрес (веб-адрес) изображения
style Определяет встроенный CSS стиль для элемента
title Определяет дополнительную информацию про элемент (отображается как всплывающая подсказка)

Полный список всех атрибутов для каждого HTML элемента приведён в: HTML Справочнике атрибутов на нашем сайте W3Schools на русском.

HTML Attributes Explained

HTML Attributes Explained

HTML elements can have attributes, which contain additional information about the element.

HTML attributes generally come in name-value pairs, and always go in the opening tag of an element. The attribute name says what type of information you’re providing about the element, and the attribute value is the actual information.

For example, an anchor ( <a> ) element in an HTML document creates links to other pages, or other parts of the page. You use the href attribute in the opening <a> tag to tell the browser where the link sends a user.

Here’s an example of a link that sends users to freeCodeCamp’s home page:

Notice that the attribute name ( href ) and value (“www.freeCodeCamp.org”) are separated with an equals sign, and quotes surround the value.

There are many different HTML attributes, but most of them only work on certain HTML elements. For example, the href attribute won’t work if it’s placed in an opening <h1> tag.

In the example above, the value supplied to the href attribute could be any valid link. However, some attributes only have a set of valid options you can use, or values need to be in a specific format. The lang attribute tells the browser the default language of the contents in an HTML element. The values for the lang attribute should use standard language or country codes, such as en for English, or it for Italian.

Boolean Attributes

Some HTML attributes don’t need a value because they only have one option. These are called Boolean attributes. The presence of the attribute in a tag will apply it to that HTML element. However, it’s okay to write out the attribute name and set it equal to the one option of the value. In this case, the value is usually the same as the attribute name.

For example, the <input> element in a form can have a required attribute. This requires users to fill out that item before they can submit the form.

Here are examples that do the same thing:

You can read more about the <a href>, <a target>, <script> src, and roll attributes here:

<a href> Attribute

<script> src Attribute

roll Attribute

<a target> Attribute

Now let’s learn more about some other HTML attributes:

P Align Attribute

Important

This attribute is not supported in HTML5. It is recommended to use the text-align CSS property.

To align the text inside a <p> tag, this attribute will help.

Syntax

Attributes

  • left — Text aligns to the left
  • right — Text aligns to the right
  • center — Text aligns to the center
  • justify — All lines of text have equal width

Example

Img Src Attribute

The <img src> attribute refers to the source of the image you want to display. The img tag will not display an image without the src attribute. However, if you set the source to the location of the image, you can display any image.

There is an image of the freeCodeCamp Logo located at https://avatars0.githubusercontent.com/u/9892522?v=4&s=400

You can set that as the image using the src attribute.

The above code displays like this:

The src attribute is supported by all browsers.

You can also have a locally hosted file as your image.

For example, <img src font-size-attribute»>Font Size Attribute

This attribute specifies the font size as either a numeric or relative value. Numeric values range from 1 to 7 with 1 being the smallest and 3 the default. It can also be defined using a relative value, like +2 or -3 , which set it relative to the value of the size attribute of the <basefont> element, or relative to 3 , the default value, if none does exist.

Note : The size attribute of <font> is not supported in HTML5. Use CSS instead.

Font Color Attribute

This attribute is used to set a color to the text enclosed in a <font> tag.

Syntax:

Hex code attribute

Autofocus Attribute

The autofocus attribute is a boolean attribute.

When present, it specifies that the element should automatically get input focus when the page loads.

Only one form element in a document can have the autofocus attribute. It cannot be applied to <input type=»hidden»> .

Applies to

ElementAttribute <button> autofocus <input> autofocus <select> autofocus <textarea> autofocus

Example

Compatibility

This is an HTML5 attribute.

Onclick Event Attribute

When the element is clicked fires a event.

It works just like the onclick method or addEventListener(‘click’) to the element.

event can be a JavaScript function or you can write raw JavaScript

Examples

Changing the color of a <p> element when clicked

Using raw JavaScript onclick attribute:

Img Align Attribute

The align attribute of an image specifies where the image should be aligned according to the surrounding element.

Attribute Values:
right — Align image to the right left — Align image to the left
top — Align image to the top
bottom — Align image to the bottom
middle — Align image to the middle

We can also align in right if we want:

Please note the align attribute is not supported in HTML5, and you should use CSS instead. However, it is still supported by all the major browsers.

Input Type Attribute

The input type attribute specifies the type of the input the user should put in your form.

text

One line of a text.

password

One line of a text. Text is automatically displayed as a series of dots or asterisks (depends on the browser and OS).

email

The HTML checks if the input matches the e-mail address format (something@something).

number

Allow only numeric input. You can also specify the min and max value allowed. The example below check that the input is number between 1 and 120.

radio

Only one option can be selected by the user. The group of radio buttons need to have the same name attribute. You can select automatically one option by using checked property (in example below the value Blue is selected).

checkbox

User can select zero or more options from the group of checkboxes. You can use checked property here too for one or more options.

button

The input is displayed as button, the text which should be displayed in the button is in value attribute.

submit

Displays the submit button. The text which should be displayed in the button is in value attribute. After clicking on the button, the HTML do the validation and if it passes, the form is submitted.

reset

Displays the reset button. The text which should be displayed in the button is in value attribute. After clicking on the button, all values from the form are deleted.

HTML Attributes

HTML attributes are used within the opening tag. They provide additional information about HTML elements. An attribute edits the default functionality of an element or offers functionality to specific element types that cannot function properly without them. The attribute has a name, followed by the equals sign(=) and a value placed inside the quotation marks(«»).

Syntax

The href attribute

The HTML <a> tag creates a link, the address of which is defined in the href attribute. In the example below, we have used the <a> tag with href attribute. Between the quotation marks we wrote the address of the page where we will go after clicking the link.

Example of the HTML <a> tag with the href attribute:

Result

The id attribute

The HTML id attribute defines a unique id for each element.

Example of the HTML <div> tag with the id attribute:

The style attribute

The style attribute defines the styling of an element, such as color, size, font and so on.

Example of the HTML <p> tag with the style attribute:

The start attribute

The start attribute defines the start value of the first list item in an ordered list.

Example of the HTML <ol> tag with the start attribute:

Multiple Attributes

You can add more than one attributes to the HTML element. Be sure to add space between them.

It doesn’t matter in what sequence attributes are placed.

Syntax

Example of the HTML <img> tag with the src , width , height and alt attributes:

Content and IDL Attributes

In HTML, we have two groups of attributes: the content attribute and the IDL (Interface Definition Language) attribute.

The content attribute is set from the content (the HTML code) and you can set get it through the element.setAttribute() or element.getAttribute().Some content attributes, like readonly , disabled , required , are also called boolean attributes. A boolean attribute’s value is true, if it is present and false, if it is absent.

The IDL attributes are the ones that can be read or set with such JavaScript properties like element.foo. The IDL attributes reflect the content attributes. They always use the content attribute and return a value when you get it, saving something in the content attribute when setting it.

The list of the mostly used HTML Attributes:

Attribute Description Example
alt Defines an alternate text when the original element is not displayed. alt=»HTML Attributes»
height Defines the height of the element. height=»250″
href Defines the URL for a link. href=»https://www.w3docs.com/»
hreflang Defines the language of the linked document. hreflang=»en»
id Defines a unique id for an HTML element. id=»example»
lang Defines the language of the document (used in <html> tag). <html lang=»en-US»>
rel Defines the relationship between the target and linked documents. rel=»nofollow»
shape Defines the shape of the element. shape=»circle»
span Groups inline-elements in a document. span=»2″
src Defines the source of the element. src=»https://www.w3docs.com/learn-html/image.jpg»
start Sets the start value of an ordered list (used in <ol> tag). <ol start=»30″>
style Sets the CSS style of an HTML element (size, font, color, etc.). style=»color:red;text-align:right»
target Defines where to open the link. target=»_blank»
wrap Defines whether the text must be wrapped or not. wrap=»hard»
width Defines the width of the element. width=»120″

See also a list of HTML Global Attributes that can be used with any HTML element.

HTML Attributes

HTML has abundant availability of attributes. Each element may have one or a few attributes used to define different properties of a particular HTML element. There are several types of HTML elements. Let us now understand the HTML attributes.

What Are Attributes in HTML?

An attribute is a property name used to provide supplementary information about HTML elements. Some common examples of HTML attributes are id, class, align, etc. Many attributes are defined globally and are applied to any element, whereas we use some of them only for specific HTML elements. The syntax is:

You can define an attribute as the characteristics of any HTML tag that needs to be placed within the opening tag.

  1. a name and
  2. a value

Names of attributes and their values are not case-sensitive. But according to the World Wide Web Consortium (W3C), it is recommended to use lowercase names and values. For an attribute, the name defines the property to be implemented. For example, BODY Tag, <body> carries many attributes such as bgcolor, background that you can implement for indicating the back color of your webpage, or give a specific image or background texture to your page, respectively.

The value defines the value which you want to assign to the property and is set within quotations.

Core Attributes

  1. id
  2. title
  3. class
  4. style

Let’s discuss these special attributes:

id Attribute

The id attribute can be applied to assign a unique identity to any element. There can be two primary reasons for using the id attribute on an HTML element. The id attribute provides a unique identifier, which ultimately makes it possible to identify the element. When you have two elements of the same name within the same script, the id attribute helps to distinguish two similar elements through the unique ID.

title Attribute

This attribute gives a recommended title for your element. Its behavior depends on the element upon which it’s implemented, even though this is often implemented to display a tooltip if the cursor hovers (comes over) the element.

class Attribute

This attribute is implemented by combining an element through a stylesheet (CSS) and identifying its class element. For more about the class attribute, you can follow the Cascading Style Sheet (CSS).

Here’s an example of a class attribute:

style Attribute

This attribute gives you a chance for specifying the rules for Cascading Style Sheet (CSS) in your element.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *