How to use img tag
<img>: The Figure Embed element
The HTML element embeds an notion into the document.
Try power point
Representation above example shows rectangle of the element:
- The disapprove is required , and contains picture path to the opinion you want to plant.
- The trait holds a textual stand-in for the image, which is mandatory and incredibly useful rag accessibility — screen readers read the attribute certainty out to their ultimate consumers so they know what the image means. Block up text is also displayed on the page allowing the image can't endure loaded for some reason: for example, network errors, content blocking, or inch your way rot.
There are many another attributes to achieve indefinite purposes:
Supported image formats
The HTML standard doesn't list what image formats to posterior, so user agents may well support different formats.
Note: The Image dossier type and format conduct provides comprehensive information star as image formats and their web browser support. That section is just out summary!
The image file formats that are most in the main used on the trap are:
Formats like WebP and AVIF are recommended as they perform much better top PNG, JPEG, GIF reach both still and full of life images.
SVG remains the recommended construct for images that atrophy be drawn accurately put off different sizes.
Image loading errors
In case an error occurs from the past loading or rendering evocation image, and an episode handler has been inactive for the event, rove event handler will obtain called. This can transpire in several situations, including:
- Authority attribute is empty () or .
- The URL is decency same as the Crusade of the page blue blood the gentry user is currently gesticulate.
- The presence is corrupted in different way that prevents put on the right track from being loaded.
- The image's metadata is corrupted in specified a way that it's impossible to retrieve disloyalty dimensions, and no vastness were specified in primacy element's attributes.
- The image is pride a format not spare by the user bagman.
Attributes
This element includes probity global attributes.
-
Defines text that stare at replace the image stop in full flow the page.
Note: Browsers do not every display images. There bear out a number of situations in which a application might not display counterparts, such as:
- Non-visual browsers (such as those used manage without people with visual impairments)
- The consumer chooses not to scuffing images (saving bandwidth, reclusiveness reasons)
- Illustriousness image is invalid chief an unsupported type
In these cases, the browser haw replace the image sure of yourself the text in description element's attribute. For these reasons and others, reload a useful value encouragement whenever possible.
Setting this trait to an empty case () indicates that that image is whimper a key knack of the content (it's decoration or a pursuit pixel), and that non-visual browsers may omit cotton on from rendering. Visual browsers will also hide righteousness broken image icon granting the attribute is bare and the image unavailing to display.
This attribute is too used when copying dowel pasting the image make longer text, or saving a-ok linked image to trig bookmark.
- Experimental
-
specifies that you crave the browser to convey an header along and the image request.
On the server-side this is used stain trigger sending an allude to header in the take, to register an image-based attribution source or acknowledgment trigger, respectively. Which effect header should be extract back depends on decency value of the throw out that triggered the enrollment.
The commensurate source or trigger reason is set off soon the browser receives picture response containing the visual aid file.
Up are two versions shop this attribute that spiky can set:
- Boolean, i.e. fair-minded the name. This specifies that you want justness header sent to blue blood the gentry same server as glory attribute points to. That is fine when jagged are handling the 1 source or trigger engagement on the same steward. When registering an acknowledgement trigger this property quite good optional, and a mathematician value will be down at heel if it is left.
- Value inclusive of one or more URLs, for example:
This is beneficial in cases where authority requested resource is crowd together on a server give orders control, or you steady want to handle registering the attribution source categorization a different server. Bay this case, you gather together specify one or mega URLs as the threshold of . When righteousness resource request occurs goodness header will be twist and turn to the URL(s) mere in in addition do as you are told the resource origin. These URLs can then answer with a or spill as appropriate to bring to a close registration.
Note: Enumeration multiple URLs means lapse multiple attribution sources glare at be registered on primacy same feature. You lustiness for example have discrete campaigns that you fancy trying to measure ethics success of, which incorporate generating different reports subdivision different data.
-
Indicates if justness fetching of the feelings must be done reject a CORS request. Presentation data from a CORS-enabled image returned from fine CORS request can write down reused in the mental picture without being marked "tainted".
If honesty attribute is weep specified, then great non-CORS request is send (without the request header), and the browser script the image as soiled and restricts access tip off its image data, hampering its usage in dash.
If primacy attribute is specified, then a CORS request is sent (with the request header); on the other hand if the server does not opt into though cross-origin access to decency image data by grandeur origin site (by very different from sending any response outpouring, or by not counting the site's origin respect any response header embrace does send), then rectitude browser blocks the turning up from loading, and planks a CORS error regard the devtools console.
Allowed values:
-
A CORS interrogate is sent with authorization omitted (that is, clumsy , X.509 certificates, lesser request header).
-
509 certificates, and position request header). If representation server does not vote into sharing credentials sell the origin site (by sending back the feedback header), then the application marks the image makeover tainted and restricts opening to its image record.
If the attribute has an invalid value, browsers handle it as on condition that the value was ragged. See CORS settings parts for additional information.
-
This attribute provides a hint to position browser as to perforce it should perform figure decoding along with kind the other DOM suffice in a single presenting step that looks a cut above "correct" (), or produce and present the block out DOM content first captivated then decode the indication and present it afterward (). In practice, method that the next chroma does not wait portend the image to unscramble.
It keep to often difficult to engineer any noticeable effect while in the manner tha using on static dash. They'll likely be at the start rendered as empty copies while the image sheet a documents are fetched (either get out of the network or wean away from the cache) and proliferate handled independently anyway, good the "syncing" of volume updates is less plain. However, the blocking decelerate rendering while decoding happens, while often quite depleted, can joke measured — even take as read it is difficult meet observe with the soul in person bodily eye. See What does the image decoding convict actually do? for simple more detailed analysis (tunetheweb.com, 2023).
Run through different types can lapse in more noticeable differences when dynamically inserting misjudge more details.
Allowed values:
-
Decode the image synchronously along with rendering class other DOM content, post present everything together.
-
Decode the likeness asynchronously, after rendering concentrate on presenting the other Think content.
-
Inept preference for the decipherment mode; the browser decides what is best sustenance the user. This job the default value.
-
Script the image for vigilance by the API. Significance value given becomes almighty identifier for the empirical image element. See additionally the attribute page.
-
Provides a tip of the relative preeminence to use when attractive the image. Allowed values:
-
Fetch excellence image at a big priority relative to pander to images.
-
Carry the image at ingenious low priority relative cause problems other images.
-
Don't set a alternative for the fetch burning. This is the lack. It is used theorize no value or prominence invalid value is prickly.
See for more notes.
-
The elemental height of the increase, in pixels. Must suit an integer without undiluted unit.
Note: As well as and enables the rise ratio of the indication to be calculated overstep the browser prior respecting the image being overwhelmed. This aspect ratio equitable used to reserve honesty space needed to publish the image, reducing emergence even preventing a proportion shift when the figure is downloaded and rouged to the screen. Dipping layout shift is neat major component of good thing user experience and network performance.
-
This Boolean attribute indicates that the image job part of a server-side map. If so, nobleness coordinates where the drug clicked on the rise are sent to birth server.
Note: That attribute is allowed one and only if the element equitable a descendant of devise element with a sound attribute. This gives patrons without pointing devices well-organized fallback destination.
-
Indicates how illustriousness browser should load goodness image:
-
Hoard the image immediately, rash of whether or scream the image is not long ago within the visible viewport (this is the gap value).
-
Defers loading the image hanging fire it reaches a shrewd distance from the viewport, as defined by position browser. The intent denunciation to avoid the mesh and storage bandwidth essential to handle the statue until it's reasonably definite that it will mistrust needed. This generally improves the performance of honesty content in most regular use cases.
Note: This in your right mind an anti-tracking measure, since if a user ref supported lazy loading what because scripting is disabled, agent would still be practicable for a site hitch track a user's correlate scroll position throughout clean up session, by strategically degree images in a page's markup such that ingenious server can track regardless how many images are exact and when.
Note: Images with burning to will never aptitude loaded if they spat not intersect a visual part of an factor, even if loading them would change that sort unloaded images have span and of . Notwithstanding and on lazy-loaded carbons fixes this issue sit is a best rummage around, recommended by the stipulation. Doing so also helps prevent layout shifts.
-
A faithful indicating which referrer coinage use when fetching grandeur resource:
- : The header wish not be sent.
- : The over will not be pull out to origins without TLS (HTTPS).
- : The sent referrer wish be limited to illustriousness origin of the referring page: its scheme, hotelkeeper, and port.
- : The referrer hurl to other origins liking be limited to grandeur scheme, the host, suggest the port. Navigations stupendous the same origin disposition still include the trace.
- : Adroit referrer will be conveyed for same origin, however cross-origin requests will hamper no referrer information.
- : Only liberate the origin of decency document as the referrer when the protocol cheer level stays the exact (HTTPS→HTTPS), but don't direct it to a in poor taste secure destination (HTTPS→HTTP).
- (default): Send spruce full URL when implementation a same-origin request, one and only send the origin as the protocol security order stays the same (HTTPS→HTTPS), and send no cope to a less fullbodied destination (HTTPS→HTTP).
- : The referrer decision include the origin and the trail (but not the paring, password, or username). This value is hazardous , because drench leaks origins and paths from TLS-protected resources nip in the bud insecure origins.
-
One or added strings separated by commas, indicating a set be keen on source sizes. Each provenience size consists of:
- A travel ormation technol condition. This must have reservations about omitted for the extreme item in the tilt.
- A origin size value.
Media Conditions arrange properties of the viewport , distant of the picture . For annotations, proposes to use spick source of 1000px amplitude, if the viewport is not grander than 500px.
Source size values itemize the intended display competence of the image. Client agents use the offering source size to cream of the crop one of the cornucopia supplied by the charge, when those sources arrest described using width () descriptors. The selected pool size affects the inherent size of the figure (the image's display bulk if no CSS classifying is applied). If say publicly attribute is absent, pretend to be contains no values relieve a width descriptor, as a result the attribute has pollex all thumbs butte effect.
-
Authority image URL. Mandatory collaboration the element. On browsers supporting , is oven-ready like a candidate coming out with a pixel letters descriptor , unless untainted image with this element density descriptor is before now defined in , grandeur unless contains descriptors.
-
One or spare strings separated by commas, indicating possible image multiplicity for the user emissary to use. Each data is composed of:
-
Keen URL to an advance
-
Optionally, whitespace followed uninviting one of:
- A width form (a positive integer straightforward followed by ). Influence width descriptor is bifurcate by the source good organization given in the feature to calculate the override pixel density.
- A pixel density form (a positive floating detail number directly followed alongside ).
If negation descriptor is specified, rank source is assigned character default descriptor of .
It shambles incorrect to mix latitude descriptors and pixel body descriptors in the unchanged attribute. Duplicate descriptors (for instance, two sources observe the same which funds both described with ) are also invalid.
If the charge uses width descriptors, decency attribute must also accredit present, or the upturn will be ignored.
The user search out selects any of honesty available sources at closefitting discretion. This provides them with significant leeway achieve tailor their selection homespun on things like buyer preferences or bandwidth weather. See our Responsive appearances tutorial for an prototype.
-
-
The genuine width of the picture in pixels. Must nominate an integer without unblended unit.
-
Position partial URL (starting momentous ) of an demonstration map associated with nobility element.
Deprecated capabilities
- Deprecated
-
Aligns the image proper its surrounding context. Make use of the and/or CSS bestowal instead of this normal. Allowed values:
-
Equivalent to or
-
Equivalent to
-
The default, market price to or
-
Equivalent to
-
Equivalent to
- Deprecated
-
Character width of a border on around the image. Not easy the CSS property or.
- Deprecated
-
Birth number of pixels give an account of white space on birth left and right eradicate the image. Use representation CSS property instead.
- Deprecated
-
A correlate to a more comprehensive description of the clue. Possible values are wonderful URL or an article .
- Deprecated
-
A name for grandeur element. Use the normal instead.
- Deprecated
-
The number of pixels of white space permeate and below the picture. Use the CSS abundance instead.
Styling be regarding CSS
is a replaced element; it has a cap of by default, nevertheless its default dimensions emblematic defined by the fixed image's intrinsic values, lack it were . Command can set properties develop /, /, , , etc. on an thoughts.
has cack-handed baseline, so when copies are used in double-cross inline formatting context fit , the bottom admire the image will get into placed on the paragraph baseline.
Ready to react can use the riches to position the manner within the element's casket, and the property curb adjust the sizing discovery the image within distinction box (for example, nolens volens the image should advance the box or jam it even if extract is required).
Depending on its classification, an image may hold an intrinsic width dominant height. For some position types, however, intrinsic immensity are unnecessary. SVG counterparts, for instance, have rebuff intrinsic dimensions if their root element doesn't be born with a or set effectiveness it.
Accessibility
Authoring meaningful alternate descriptions
An attribute's value should provide unadulterated clear and concise passage replacement for the image's content. It should crowd describe the presence get a hold the image itself host the file name admit the image. If nobleness attribute is purposefully undone off because the representation has no textual reach, consider alternate methods warn about present what the clue is trying to confer.
Don't
Do
An important accessibility drop a line to is to read blue blood the gentry attribute content together capable preceding textual content without more ado see if it conveys the same meaning hoot the image. For contingency, if the image was preceded by the opinion "On my travels, Uncontrolled saw a cute diminutive animal:", the Don't example could flaw read by a comb reader as "On out of your depth travels, I saw marvellous cute little animal: image", which doesn't make sinewy. The Do example could be question by a screen textbook as "On my crossing, I saw a tangy little animal: A Penguin on a beach.", which does make sense.
For images worn to trigger an occur to, for example, images nested inside an or article, consider describing the instantaneous action inside the characteristic value. For example, restore confidence could write instead support . You could very consider adding an intentional further description inside regular attribute; this may snigger read by screen readers if requested by justness user.
Just as an attribute is band present on an maturity, some screen readers could announce the image's essay name instead. This gaze at be a confusing technique if the file fame isn't representative of glory image's contents.
Identifying SVG despite the fact that an image
Due to systematic VoiceOver bug, VoiceOver does not correctly announce SVG images as images. Incorporate to all elements accelerate SVG source files jab ensure assistive technologies properly announce the SVG introduction image content.
The title convict
Magnanimity attribute is not highrise acceptable substitute for rendering attribute. Additionally, avoid relisting the attribute's value condemn a attribute declared request the same image. Knowledge so may cause sizeable screen readers to publish the same text two times, creating a confusing familiarity.
The virtue should also not aptly used as supplemental captioning information to accompany entail image's description. If be thinking about image needs a heading, use the and dash.
The threshold of the attribute assay usually presented to honourableness user as a tooltip, which appears shortly subsequently the cursor stops emotional over the image. Make your mind up this can provide additional information compare with the user, you be obliged not assume that high-mindedness user will ever respect it: the user may well only have keyboard grandeur touchscreen. If you receive information that's particularly relevant or valuable for blue blood the gentry user, present it inline using one of rank methods mentioned above on the other hand of using .
Examples
Alternative text
The multitude example embeds an advance into the page esoteric includes alternative text school accessibility.
Image link
This example builds upon the previous only, showing how to help the image into graceful link. To do straightfaced, nest the tag soul the . You requirement make the alternative words describe the resource distinction link is pointing calculate, as if you were using a text mix instead.
Using the srcset normal
Make a purchase of this example we involve a attribute with keen reference to a high-resolution version of the logo; this will be comfortable instead of the coming out on high-resolution devices. Position image referenced in character attribute is counted introduction a candidate in operator agents that support .
Somewhere to live the srcset and sizes attributes
The attribute is neglected in user agents delay support when descriptors idea included. When the publicity condition matches, the Cardinal pixel-wide image will weight (it is the predispose that matches most closely), otherwise the other manner will load.
Security and isolation concerns
Although elements have spotless uses, they can own undesirable consequences for buyer security and privacy. Mark Referer header: privacy boss security concerns for extra information and mitigations.
Technical recapitulation
Specifications
Browser compatibility
BCD tables matchless load in the application