Atributos HTML
Los atributos HTML se usan dentro de la etiqueta de apertura. Proporcionan información adicional sobre los elementos HTML. Un atributo proporciona metadatos para un elemento o modifica su comportamiento. El atributo tiene un nombre, seguido del signo igual (=) y un valor colocado entre comillas (").
Sintaxis
Sintaxis de los atributos HTML
<tag attribute="value">Your Text</tag>El atributo href
La etiqueta HTML <a> crea un enlace, cuya dirección se define en el atributo href. En el ejemplo siguiente, hemos usado la etiqueta <a> con el atributo href. Entre las comillas escribimos la dirección de la página a la que iremos después de hacer clic en el enlace.
Ejemplo de la etiqueta HTML <a> con el atributo href:
Ejemplo de atributo
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<a href="https://www.w3docs.com">Click here and go to the homepage.</a>
</body>
</html>Resultado
Haz clic y ve a la página principal
El atributo id
El atributo id de HTML define un id único para cada elemento.
Ejemplo de la etiqueta HTML <div> con el atributo id:
Ejemplo de la etiqueta div con el atributo "id"
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
#text {
font-family: sans-serif;
font-size: 20px;
line-height: 28px;
color: #777777;
}
</style>
</head>
<body>
<h2>Example of the div tag with the "id" attribute</h2>
<div id="text">Here is some text for the div tag with the "id" attribute.</div>
</body>
</html>El atributo style
El atributo style define el estilo de un elemento, como color, tamaño, fuente, etc.
Ejemplo de la etiqueta HTML <p> con el atributo style:
Ejemplo de la etiqueta p con el atributo "style":
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h2>Example of the p tag with the style attribute</h2>
<p style="color:#666666;font-size:18px;">Here is some text for the p tag with the "style" attribute.</p>
</body>
</html>El atributo start
El atributo start define el valor inicial del primer elemento de una lista en una lista ordenada.
Ejemplo de la etiqueta HTML <ol> con el atributo start:
Ejemplo de la etiqueta ol con el atributo "start"
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h1>Example of the ol tag with the "start" attribute:</h1>
<ol>
<li>List Item</li>
<li>List Item </li>
<li>List Item </li>
</ol>
<ol start="30">
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
</ol>
</body>
</html>Múltiples atributos
Puedes añadir más de un atributo al elemento HTML. Asegúrate de dejar un espacio entre ellos.
No importa en qué secuencia se coloquen los atributos.
Sintaxis
Ejemplo de atributos HTML
<tag attribute1="value" attribute2="value">Your text</tag>Ejemplo de la etiqueta HTML <img> con los atributos src, width, height y alt:
Ejemplo de la etiqueta img de HTML con múltiples atributos
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h1>Heading</h1>
<p>This is Aleq's photo</p>
<img src="https://es.w3docs.com/uploads/media/default/0001/01/25acddb3da54207bc6beb5838f65f022feaa81d7.jpeg" alt="Aleq" width="200" height="185"/>
</body>
</html>Atributos de contenido y atributos IDL
En HTML, tenemos dos grupos de atributos: el atributo de contenido y el atributo IDL (Interface Definition Language).
El atributo de contenido se establece a partir del contenido (el código HTML) y puedes obtenerlo mediante element.setAttribute() o element.getAttribute(). Algunos atributos de contenido, como readonly, disabled, required, también se llaman atributos booleanos. El valor de un atributo booleano es true si está presente y false si está ausente.
Los atributos IDL son los que se pueden leer o establecer con propiedades de JavaScript como element.foo. Los atributos IDL reflejan los atributos de contenido. Siempre usan el atributo de contenido y devuelven un valor cuando lo obtienes, guardando algo en el atributo de contenido al establecerlo.
La lista de los atributos HTML más usados:
| 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 | Defines the number of columns spanned by a <col> or <colgroup> element. | span="2" |
| src | Defines the source of the element. | src="https://example.com/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" |
Consulta también una lista de atributos globales de HTML que pueden usarse con cualquier elemento HTML.
La lista completa de atributos HTML:
| Attribute | Belongs to | Description |
|---|---|---|
| accept | <input> | Defines the kinds of files that are accepted by the server (only for type="file"). |
| accept-charset | <form> | Defines the character encodings used for the form submission. |
| accesskey | Global Attributes | Defines a shortcut key that will activate an element. |
| action | <form> | Defines where the form-data should be sent when a form is submitted. |
| align | HTML5 doesn’t support this attribute. | Defines the alignment according to nearby elements. CSS can be used instead of this attribute. |
| alt | <area>, <img>, <input> | Defines an alternate text if the original element doesn’t display. |
| async | <script> | Defines that the script is executed asynchronously. It is used only for external scripts. |
| autocomplete | <form>, <input> | Defines whether the autocomplete of the <form> or the <input> elements should be enabled. |
| autofocus | <button>, <input>, <select>, <textarea> | Defines that the element must automatically get focus when the page loads. |
| autoplay | <audio>, <video> | Defines that the audio or video will start playing when it is ready. |
| bgcolor | HTML5 doesn’t support this attribute. | Defines the background color of an element. CSS can be used instead of this attribute. |
| border | HTML5 doesn’t support this attribute. | Defines the width of the border of an element. CSS can be used instead of this attribute. |
| charset | <meta>, <script> | Defines the character encoding. |
| checked | <input> | Defines that an <input> element must be pre-selected when the page loads (for type="checkbox" or type="radio"). |
| cite | <blockquote>, <del>, <ins>, <q> | Defines a URL explaining the quote, deleted or inserted text. |
| class | Global Attributes | Defines one or more class names for an element. |
| color | HTML5 doesn’t support this attribute. | Defines the text color of an element. CSS can be used instead of this attribute. |
| cols | <textarea> | Defines the visible width of a text area. |
| colspan | <td>, <th> | Defines the number of columns that should be spanned by a table cell. |
| content | <meta> | Gives the value related the http-equiv or name attribute. |
| contenteditable | Global Attributes | Defines whether the content of an element can be edited or not. |
| controls | <audio>, <video> | Defines that audio or video controls must be displayed (for example a play or pause button and so on). |
| coords | <area> | Defines the coordinates of the area. |
| data | <object> | Defines the URL of the resource that will be used by the object. |
| data-* | Global Attributes | Stores custom data private to the page or application. |
| datetime | <del>, <ins>, <time> | Defines the date and time. |
| default | <track> | Defines that the track will be enabled if the preferences of the user don’t point out that another track would be more proper. |
| defer | <script> | Defines that the script is executed when the page finishes parsing. This attribute is used only for external scripts. |
| dir | Global Attributes | Defines the text direction for an element’s content. |
| dirname | <textarea>, <input> | Defines that the text direction will be submitted. |
| disabled | <button>, <fieldset>, <input>, <optgroup>, <option>, <select>, <textarea> | Defines that the specified element or group of elements must be disabled. |
| download | <a>, <area> | Defines that the target will be downloaded when a user clicks on the hyperlink. |
| draggable | Global Attributes | Defines if an element is draggable or not. |
| dropzone | Global Attributes | Defines if the dragged data is copied, moved, or linked, when it is dropped. |
| enctype | <form> | Defines how the form-data should be encoded when it is submitted to the server. This attribute is used only for method="post". |
| for | <label>, <output> | Specifies which form element(s) a label or calculation is linked to. |
| form | <button>, <fieldset>, <input>, <label>, <meter>, <object>, <output>, <select>, <textarea> | Defines the name of the form that the element belongs to. |
| formaction | <button>, <input> | Defines where to send the form-data when a form is submitted. This attribute is used only for type="submit". |
| headers | <th>, <th> | Defines one or more header cells a cell is connected with. |
| height | <canvas>, <embed>, <iframe>, <img>, <input>, <object>, <video> | Defines the height of the element. |
| hidden | Global Attributes | Defines that an element is not relevant. |
| high | <meter> | Defines the upper bound of the range represented by the <meter> element. |
| href | <a>, <area>, <base>, <link> | Defines the URL of the page where the link goes to. |
| hreflang | <a>, <area>, <link> | Defines the language of the linked document. |
| http-equiv | <meta> | Gives the content attribute an HTTP header for the information or value. |
| id | Global Attributes | Defines a unique id for an element. |
| ismap | <img> | Defines an image as a server-side image-map. |
| kind | <track> | Defines the kind of text track. |
| label | <track>, <option>, <optgroup> | Defines the title of the text track. |
| lang | Global Attributes | Defines the language of the content of an element. |
| list | <input> | Cites a <datalist> element containing pre-defined options for an <input> element. |
| loop | <audio>, <video> | Defines that the audio or video will start again, every time when it is finished. |
| low | <meter> | Defines the range considered to be a low value. |
| max | <input>, <meter>, <progress> | Defines the maximum value. |
| maxlength | <input>, <textarea> | Defines the maximum number of characters that an element can contain. |
| media | <a>, <area>, <link>, <source>, <style> | Defines what media or device the linked document is optimized for. |
| method | <form> | Defines the HTTP method that should be used when sending form-data. |
| min | <input>, <meter> | Defines a minimum value. |
| multiple | <input>, <select> | Defines that more than one value can be entered by the user. |
| muted | <audio>, <video> | Defines that the audio output of the video must be muted. |
| name | <button>, <fieldset>, <form>, <iframe>, <input>, <map>, <meta>, <object>, <output>, <param>, <select>, <textarea> | Defines the name of the element. |
| novalidate | <form> | Defines that the form mustn’t be validated when it is submitted. |
| onabort | <audio>, <embed>, <img>, <object>, <video> | Script that runs on abort. |
| onafterprint | <body> | Script that runs after the document is printed. |
| onbeforeunload | <body> | Script that runs when the document is going to be unloaded. |
| onblur | All visible elements. | Script that runs when the element loses its focus. |
| oncanplay | <audio>, <embed>, <object>, <video> | Script that runs when a file is ready to start playing. |
| oncanplaythrough | <audio>, <video> | Script that runs when a file can be played till the end without pausing for buffering. |
| onchange | All visible elements. | Script that runs when the value of the element is changed. |
| onclick | All visible elements. | Script that runs when the element is clicked. |
| oncontextmenu | All visible elements. | Script that runs when a context menu is triggered. |
| oncopy | All visible elements. | Script that runs when the content of the element is copied. |
| oncuechange | <track> | Script that runs when the cue in a <track> element changes. |
| oncut | All visible elements. | Script that runs when the content of the element is cut. |
| ondblclick | All visible elements. | Script that runs when the element is double-clicked. |
| ondrag | All visible elements. | Script that runs when the element is dragged. |
| ondragend | All visible elements. | Script that runs at the end of a drag operation. |
| ondragenter | All visible elements. | Script that runs when an element has been dragged to a valid drop target. |
| ondragleave | All visible elements. | Script that runs when an element leaves a valid drop target. |
| ondragover | All visible elements. | Script that runs when an element is dragged over a valid drop target. |
| ondragstart | All visible elements. | Script that runs at the start of a drag operation. |
| ondrop | All visible elements. | Script that runs at the beginning of a drag operation. |
| ondurationchange | <audio>, <video> | Script that runs when the length of the media changes. |
| onemptied | <audio>, <video> | Script that runs when something unexpected happens and the file becomes unavailable. |
| onended | <audio>, <video> | Script that runs when the media reaches the end. |
| onerror | <audio>, <video>, <embed>, <object>, <script>, <style>, <body> | Script that runs when an error occurs. |
| onfocus | All visible elements. | Script that runs when the element gets focus. |
| onhashchange | <body> | Script that runs when the anchor changes. |
| oninput | All visible elements. | Script that runs when the element catches user input. |
| oninvalid | All visible elements. | Script that runs when the element is invalid. |
| onkeydown | All visible elements. | Script that runs when a user is pressing a key. |
| onkeypress | All visible elements. | Script that runs when a user presses a key. |
| onkeyup | All visible elements. | Script that runs when a user releases a key. |
| onload | <body>, <iframe>, <input>, <img>, <script>, <style>, <link> | Script that runs when the loading of the finishes. |
| onloadeddata | <audio>, <video> | Script that runs when media data is loaded. |
| onloadedmetadata | <audio>, <video> | Script that runs when meta data is loaded. |
| onloadstart | <audio>, <video> | Script that runs when the file starts loading, before anything is actually loaded. |
| onmousedown | All visible elements. | Script that runs when a mouse button presses down on an element. |
| onmousemove | All visible elements. | Script that runs as far as the mouse pointer is moving over an element. |
| onmouseout | All visible elements. | Script that runs when a mouse pointer leaves an element. |
| onmouseup | All visible elements. | Script that runs when a mouse button is released over an element. |
| onmouseover | All visible elements. | Script that runs when a mouse pointer moves over an element. |
| onmousewheel | All visible elements. | Script that runs when a mouse wheel scrolls over an element. |
| onoffline | <body> | Script that runs when the browser starts working offline. |
| ononline | <body> | Script that runs when the browser starts working online. |
| onpagehide | <body> | Script that runs when a user navigates away from a page. |
| onpageshow | <body> | Script that runs when a user navigates to a page. |
| onpaste | All visible elements. | Script that runs when some content is pasted in an element. |
| onpause | <audio>, <video> | Script that runs when the media is paused. |
| onplay | <audio>, <video> | Script that runs when the media starts playing. |
| onplaying | <audio>, <video> | Script that runs when the media is playing. |
| onpopstate | <body> | Script that runs when the history of the windows changes. |
| onprogress | <audio>, <video> | Script that runs when the browser is in the process of getting the media data. |
| onratechange | <audio>, <video> | Script that runs when the playback rate changes. |
| onreset | <form> | Script that runs when a reset button in a form is clicked. |
| onresize | <body> | Script that runs when the browser window is resized. |
| onscroll | All visible elements. | Script that runs when the scrollbar of an element is being scrolled. |
| onsearch | <input> | Script that runs when the user writes something in a search field. |
| onseeked | <audio>, <video> | Script that runs when the seeking attribute is set to false pointing out that seeking has ended. |
| onseeking | <audio>, <video> | Script that runs when the seeking attribute is set to true and points out that seeking is active. |
| onselect | All visible elements. | Script that runs when the element is selected. |
| onstalled | <audio>, <video> | Script that runs when the browser can’t fetch the media data for some reasons. |
| onstorage | <body> | Script that runs when a Web Storage area is updated. |
| onsubmit | <form> | Script that runs when a form is submitted. |
| onsuspend | <audio>, <video> | Script that runs when fetching the media data is stopped before it is totally loaded. |
| ontimeupdate | <audio>, <video> | Script that runs when the playing position has changed. |
| ontoggle | <details> | Script that runs when the <details> element is opened or closed. |
| onunload | <body> | Script that runs when a page has unloaded. |
| onvolumechange | <audio>, <video> | Script that runs each time when the volume of a video or audio is changed. |
| onwaiting | <audio>, <video> | Script that runs when the media is paused, but at the same time is expected to continue. |
| onwheel | All visible elements. | Script that runs when the mouse wheel rolls up or down over an element. |
| open | <details> | Defines that the details should be visible. |
| optimum | <meter> | Defines what value is the optimal value for the gauge. |
| pattern | <input> | Defines a regular expression that the value of an <input> element is checked against. |
| placeholder | <input>, <textarea> | Defines a short hint describing the element’s expected value. |
| poster | <video> | Defines an image that will be shown while the video is downloading, or until the play button is hit by the user. |
| preload | <audio>, <video> | Defines if and how the audio or video should be loaded when the page loads. |
| readonly | <input>, <textarea> | Defines that the element is read-only. |
| rel | <a>, <area>, <link> | Defines the relationship between the current and the linked documents. |
| required | <input>, <textarea>, <select> | Defines that the element should be filled out before the form is submitted. |
| reversed | <ol> | Defines that the list order should be descending. For example 5,4,3... |
| rows | <textarea> | Defines the visible number of lines in a text area. |
| rowspan | <td>, <th> | Defines the number of rows that should be spanned by a table cell. |
| sandbox | <iframe> | Enables an additional set of restrictions for the content within an <iframe> element. |
| scope | <th> | Defines if a header cell is a header for a column, row, or group of columns or rows. |
| selected | <option> | Defines that an option must be pre-selected when the page loads. |
| shape | <area> | Defines the shape of the area. |
| size | <input>, <select>, <embed>, <iframe> | Defines the width, in characters (for <input>) or the number of visible options (for <select>). |
| sizes | <link>, <img>, <source> | Defines the size of the linked resource. |
| span | <col>, <colgroup> | Defines the number of columns to span. |
| spellcheck | Global Attributes | Defines if the grammar and spelling of the element should be checked or not. |
| src | <img>, <source>, <audio>, <video>, <script>, <track>, <embed>, <iframe> | Defines the URL of the media file. |
| srcdoc | <iframe> | Defines the HTML content of the page that should be shown in the <iframe> element. |
| srclang | <track> | Defines the language of the track text data. |
| srcset | <img>, <source> | Defines the URL of the image that can be used in different situations. |
| start | <ol> | Defines the start value of an ordered list. |
| step | <input> | Defines the legal number intervals for an input field. |
| style | Global Attributes | Defines an inline CSS style for an element. |
| tabindex | Global Attributes | Defines the tabbing order of an element. |
| target | <a>, <area>, <base>, <form> | Defines the target for where the linked document should be opened or where the form should be submitted. |
| title | Global Attributes | Defines additional information about an element. |
| translate | Global Attributes | Defines whether the element’s text content should be translated by the browser or translation tools. |
| type | <embed>, <input>, <object>, <a>, <button>, <link>, <menu>, <object>, <script>, <source>, <style> | Defines the type of element. |
| usemap | <object>, <img> | Defines an image as a client-side image-map. |
| value | <button>, <input>, <li>, <option>, <meter>, <progress>, <param> | Defines the value of the element. |
| width | <canvas>, <embed>, <iframe>, <img>, <input>, <object>, <video> | Defines the width of the element. |
| wrap | <textarea> | Defines how the text in a text area should be wrapped when it is submitted within a form. |
Consulta también una lista de atributos globales de HTML que pueden usarse con cualquier elemento HTML.
Práctica
¿Cuáles de las siguientes afirmaciones sobre los atributos HTML son verdaderas?