just curious.

<img src="filepath.jpeg" id="idhere?" />

or

<img id="idhere?" src="filepath.jpeg" />

which is valid? are they both vaild? and differences?

Dani AI

Generated

Short answer: attribute order does not matter — the browser treats an element's attributes as an unordered set. As pointed out, both placements are valid. What actually matters for correctness and accessibility is which attributes you include (for example, an alt value is required for meaningful images, and alt="" should be used for purely decorative ones).

Practical rules worth following: use id only when you need a single, unique identifier (JavaScript hooks, fragment links). Use class for reusable styling. Keep id values simple (no spaces, avoid starting with punctuation or a digit to keep CSS selectors straightforward) and never reuse the same id on multiple elements. Prefer explicit width/height attributes to reduce layout shift and consider loading="lazy" or srcset for performance.

Example of a clear, practical attribute order (readability, not requirement):

<img id="siteLogo" class="brand" src="images/logo.png" alt="Company logo" width="200" height="60" loading="lazy">

Notes and troubleshooting: the self-closing /> is needed for XHTML but optional in modern HTML5; either will work in most browsers, but prefer plain <img ...> in HTML5. If an image does not appear, check the path (case sensitivity on servers), network panel for 404/CORS/CSP errors, correct quoting of attributes, and correct MIME type on the server. Finally, choose and document a consistent attribute ordering for your team—readability and consistency matter more than which attribute comes first.

Recommended Answers

All 2 Replies

Both order is valid but attribute "alt" is necessary for valid "img" tag

Thank you very much Andris. Having the ID before the src is weird!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.