HTML Guides
Learn how to identify and fix common HTML validation errors flagged by the W3C Validator — so your pages are standards-compliant and render correctly across every browser. Also check our Accessibility Guides.
The poster attribute specifies an image to display as a placeholder while the video is loading or before the user starts playback. Like all HTML attributes that accept URLs — such as src, href, and action — the value must conform to valid URI syntax as defined by RFC 3986. In this standard, a literal space character is not a legal character in any part of a URL. When the validator encounters a space in the poster attribute's value, it flags it as an illegal character in the path segment.
While most modern browsers are forgiving and will attempt to resolve URLs containing raw spaces by internally encoding them, relying on this behavior is problematic for several reasons:
- Standards compliance: The HTML specification requires valid URLs. Raw spaces violate this requirement.
- Interoperability: Not all user agents, HTTP clients, or content delivery systems handle unencoded spaces the same way. Some may truncate the URL at the first space or fail to resolve the resource entirely.
- Portability: If your HTML is consumed by tools, scrapers, or APIs that strictly parse URLs, unencoded spaces can cause silent failures.
- Consistency: Keeping URLs properly encoded prevents subtle bugs when paths are constructed dynamically in server-side or client-side code.
The fix is straightforward. You have two options:
- Percent-encode the spaces: Replace every space in the URL with
%20. This preserves the original file and folder names on the server while producing a valid URL in your HTML. - Eliminate spaces from file and folder names: Use hyphens (
-), underscores (_), or camelCase instead of spaces. This is generally considered best practice for web assets, as it avoids encoding issues across the board.
Note that this rule applies to the entire URL path, not just the filename. If any directory in the path contains a space, it must also be encoded or renamed. The same principle applies to other special characters that are reserved or disallowed in URLs, such as {, }, |, ^, and [.
Examples
Incorrect — space in the path
The folder name video images contains a space, which is illegal in a URL path segment.
<video controls poster="/img/video images/snapshot.png">
<source src="/videos/sample.mp4" type="video/mp4">
</video>
Incorrect — space in the filename
The filename my poster.jpg also triggers the same error.
<video controls poster="/img/my poster.jpg">
<source src="/videos/sample.mp4" type="video/mp4">
</video>
Fixed — percent-encoding the spaces
Each space is replaced with %20, producing a valid URL.
<video controls poster="/img/video%20images/snapshot.png">
<source src="/videos/sample.mp4" type="video/mp4">
</video>
Fixed — removing spaces from the path
Renaming the folder to use a hyphen eliminates the need for encoding entirely.
<video controls poster="/img/video-images/snapshot.png">
<source src="/videos/sample.mp4" type="video/mp4">
</video>
Fixed — removing spaces from the filename
<video controls poster="/img/my-poster.jpg">
<source src="/videos/sample.mp4" type="video/mp4">
</video>
As a general best practice, avoid spaces in all file and folder names used on the web. Use hyphens or underscores instead. If you're working with files you can't rename — such as assets from a CMS or third-party system — always percent-encode spaces as %20 in your HTML. This applies not only to poster but to every attribute that takes a URL value, including src, href, action, data, and formaction.
Square brackets are not valid characters in a URL path segment and must be percent-encoded in the poster attribute of a <video> element.
The poster attribute accepts a valid URL that points to an image displayed while the video is not playing or until the first frame loads. URLs follow RFC 3986, which restricts the characters allowed in path segments. Square brackets ([ and ]) are reserved characters that are only permitted in the host component of a URL (for IPv6 addresses). When they appear in a path, query, or fragment component, they must be percent-encoded as %5B for [ and %5D for ].
This applies to any HTML attribute that expects a URL, not just poster. The same rule covers src, href, action, and similar attributes.
Invalid example
<video poster="/images/thumbnail[1].jpg" controls>
<source src="video.mp4" type="video/mp4">
</video>
Fixed example
Replace [ with %5B and ] with %5D:
<video poster="/images/thumbnail%5B1%5D.jpg" controls>
<source src="video.mp4" type="video/mp4">
</video>
If you control the file names on the server, renaming the file to avoid square brackets entirely is a simpler long term fix:
<video poster="/images/thumbnail-1.jpg" controls>
<source src="video.mp4" type="video/mp4">
</video>
The rel attribute defines the relationship between the current document and a linked resource. The HTML specification maintains a set of recognized keyword values for this attribute, and the allowed keywords vary depending on which element the attribute appears on. For example, stylesheet is valid on <link> but not on <a>, while nofollow is valid on <a> and <form> but not on <link>.
When the validator encounters a rel value that isn't a recognized keyword, it checks whether the value is a valid absolute URL. This is because the HTML specification allows custom link types to be defined using absolute URLs as identifiers (similar to how XML namespaces work). If the value is neither a recognized keyword nor a valid absolute URL, the validator raises this error.
Common causes of this error include:
- Typos in standard keywords — for example,
rel="styelsheet"orrel="no-follow"instead of the correctrel="stylesheet"orrel="nofollow". - Using non-standard or invented values — such as
rel="custom"orrel="external", which aren't part of the HTML specification's recognized set. - Using relative URLs as custom link types — for example,
rel="my-custom-type"instead of a full URL likerel="https://example.com/my-custom-type".
This matters because browsers and other user agents rely on recognized rel values to determine how to handle linked resources. An unrecognized value will simply be ignored, which could mean your stylesheet doesn't load, your prefetch hint doesn't work, or search engines don't respect your intended link relationship. Using correct values ensures predictable behavior across all browsers and tools.
Examples
Incorrect: Misspelled keyword
<link rel="styleshet" href="main.css">
The validator reports that styleshet is not a recognized keyword and is not an absolute URL.
Correct: Fixed spelling
<link rel="stylesheet" href="main.css">
Incorrect: Non-standard keyword on an anchor
<a href="https://example.com" rel="external">Visit Example</a>
The value external is not a standard rel keyword in the HTML specification, so the validator flags it.
Correct: Using a recognized keyword
<a href="https://example.com" rel="noopener">Visit Example</a>
Incorrect: Relative URL as a custom link type
<link rel="my-custom-rel" href="data.json">
Correct: Absolute URL as a custom link type
If you genuinely need a custom relationship type, provide a full absolute URL:
<link rel="https://example.com/rels/my-custom-rel" href="data.json">
Correct: Common valid rel values
Here are some frequently used standard rel keywords with their appropriate elements:
<!-- Linking a stylesheet -->
<link rel="stylesheet" href="styles.css">
<!-- Linking a favicon -->
<link rel="icon" href="favicon.ico">
<!-- Preloading a resource -->
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
<!-- Telling search engines not to follow a link -->
<a href="https://example.com" rel="nofollow">Sponsored link</a>
<!-- Opening a link safely in a new tab -->
<a href="https://example.com" target="_blank" rel="noopener noreferrer">External site</a>
Multiple rel values
You can specify multiple space-separated rel values. Each one must individually be either a recognized keyword or a valid absolute URL:
<!-- Correct: both values are recognized keywords -->
<a href="https://example.com" target="_blank" rel="noopener noreferrer">External</a>
<!-- Incorrect: "popup" is not a recognized keyword or absolute URL -->
<a href="https://example.com" target="_blank" rel="noopener popup">External</a>
To resolve this error, consult the MDN rel attribute reference for the full list of recognized keywords and which elements support them. If your value isn't on the list, either replace it with the correct standard keyword or use a complete absolute URL to define your custom link type.
required is a boolean attribute, so on <input>, <select> and <textarea> you write it bare, empty or as required="required", and a value like "true" or "false" is an error.
The HTML standard allows two values for a boolean attribute: the empty string and the attribute's own name, in any letter case. So required, required="", required="required" and required="REQUIRED" all pass. The validator reports any other value with this message and quotes what it found: "true", "false", "1", "yes", and also "required " with a trailing space.
Browsers don't read the value at all. If the attribute is there, the field is mandatory, so required="false" blocks the form just like required="true" does. To make a field optional, remove the attribute.
The bad value usually comes from a form builder or template that writes a boolean setting straight into the markup, often with aria-required="true" next to it. Once you fix required, the validator warns that aria-required is unnecessary on an element that has required, so remove it too. From JavaScript, set the property (field.required = false) or call removeAttribute("required"). Calling setAttribute("required", "false") leaves the field required.
Some details depend on the element:
<input>:requiredonly applies to types a user can leave empty or unchecked:text,search,email,url,tel,password,number, the date and time types,checkbox,radioandfile. Onhidden,range,colorand the button types (submit,reset,button,image), it isn't allowed at all, and the validator says so in a separate error. Remove it there instead of fixing the value.<textarea>: a required text area blocks the form while its value is empty. The text between the opening and closing tags is the starting value, so spaces a template adds for indentation make the field count as filled in before anyone types. Put</textarea>right after the opening tag.<select>: a required drop-down (nomultiple, and nosizeabove1) needs a placeholder as its first<option>, withvalue=""and directly inside the<select>, not in an<optgroup>. An option without avalueattribute uses its text as its value, so<option>Choose a size</option>counts as an answer, and the form submits "Choose a size" if the user never opens the list. When the first option isn't a valid placeholder, the validator reports a second error about it, even whilerequiredhas a bad value.
Invalid example
<form action="/order" method="post">
<label for="email">Email</label>
<input type="email" id="email" name="email" required="true">
<label for="size">Size</label>
<select id="size" name="size" required="true">
<option value="">Choose a size</option>
<option value="s">Small</option>
<option value="m">Medium</option>
<option value="l">Large</option>
</select>
<label for="notes">Notes (optional)</label>
<textarea id="notes" name="notes" rows="3" required="false"></textarea>
<button type="submit">Place order</button>
</form>
Valid example
<form action="/order" method="post">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
<label for="size">Size</label>
<select id="size" name="size" required>
<option value="">Choose a size</option>
<option value="s">Small</option>
<option value="m">Medium</option>
<option value="l">Large</option>
</select>
<label for="notes">Notes (optional)</label>
<textarea id="notes" name="notes" rows="3"></textarea>
<button type="submit">Place order</button>
</form>
A <button> element accepts only a short list of ARIA roles in its role attribute, and the validator rejects every other value.
The ARIA in HTML specification allows these roles on a <button>: checkbox, combobox, gridcell, link, menuitem, menuitemcheckbox, menuitemradio, option, radio, separator, slider, switch, tab and treeitem. Anything else fails: real ARIA roles like heading or img, made-up words like btn, and the presentational roles none and presentation. Some of the allowed roles bring their own requirements, such as aria-checked for switch, which the validator reports as separate errors.
role="none" usually shows up on a <button> that is only decoration, like the plus or chevron icon of an accordion, often next to tabindex="-1" and aria-hidden="true" to keep it away from keyboard and screen reader users. The role adds nothing there. Browsers ignore none and presentation on elements that can receive focus, buttons included, so the element keeps its button role.
If the element isn't a control, it shouldn't be a <button>. Put the icon in a <span> with aria-hidden="true", inside the real button, so the whole row stays clickable and screen readers skip the icon. If the element is a control, remove the role attribute, or replace it with one of the allowed roles that describes what the button does.
Invalid example
<div class="faq-question">
<h3>
<button type="button" aria-expanded="false" aria-controls="answer-1">How long does shipping take?</button>
</h3>
<button type="button" class="faq-icon" role="none" tabindex="-1" aria-hidden="true">+</button>
</div>
<div id="answer-1" hidden>Orders ship within two business days.</div>
Valid example
<h3>
<button type="button" aria-expanded="false" aria-controls="answer-1">
How long does shipping take?
<span class="faq-icon" aria-hidden="true">+</span>
</button>
</h3>
<div id="answer-1" hidden>Orders ship within two business days.</div>
The sandbox attribute is one of the most powerful security features available for <iframe> elements. When present with no value (or with specific tokens), it applies a strict set of restrictions to the embedded content — blocking scripts, form submissions, popups, same-origin access, and more. You selectively relax these restrictions by adding space-separated tokens like allow-scripts, allow-forms, or allow-popups.
The problem arises specifically when allow-scripts and allow-same-origin are used together. The allow-scripts token lets the embedded page execute JavaScript, while allow-same-origin lets it retain its original origin (rather than being treated as coming from a unique, opaque origin). With both enabled, the embedded page's JavaScript can access the parent page's DOM via window.parent (if they share the same origin) or, more critically, can use JavaScript to programmatically remove the sandbox attribute from its own <iframe> element. Once the attribute is removed, all sandboxing restrictions are lifted, making the sandbox attribute completely pointless.
This is why the W3C validator flags this combination — it's not technically invalid HTML, but it's a security anti-pattern that renders sandboxing ineffective. The WHATWG HTML specification explicitly warns against this combination for the same reason.
How to fix it
The fix depends on what the embedded content actually needs:
If the embedded page needs scripts but not same-origin access: Remove
allow-same-origin. The page can still run JavaScript but will be treated as a unique origin, preventing it from accessing cookies, storage, or the parent frame's DOM.If the embedded page needs same-origin access but not scripts: Remove
allow-scripts. The page retains its origin but cannot execute any JavaScript.If you believe both are required: Reconsider whether sandboxing is the right approach. If the embedded content truly needs both script execution and same-origin access, the
sandboxattribute provides no meaningful security benefit, and you may want to use other security mechanisms likeContent-Security-Policyheaders instead.
Always follow the principle of least privilege — only grant the permissions the embedded content strictly requires.
Examples
❌ Bad: using both allow-scripts and allow-same-origin
<iframe
src="https://example.com/widget"
sandbox="allow-scripts allow-same-origin">
</iframe>
This triggers the validator warning because the embedded page can use its script access combined with its preserved origin to break out of the sandbox entirely.
❌ Bad: both flags present alongside other tokens
<iframe
src="https://example.com/widget"
sandbox="allow-forms allow-scripts allow-same-origin allow-popups">
</iframe>
Even with additional tokens, the presence of both allow-scripts and allow-same-origin still defeats the sandbox.
✅ Good: allowing scripts without same-origin access
<iframe
src="https://example.com/widget"
sandbox="allow-scripts">
</iframe>
The embedded page can run JavaScript but is treated as a unique opaque origin, preventing it from accessing parent-page resources or removing its own sandbox.
✅ Good: allowing only the necessary permissions
<iframe
src="https://example.com/widget"
sandbox="allow-scripts allow-forms allow-popups">
</iframe>
This grants script execution, form submission, and popup capabilities while keeping the content sandboxed in a unique origin.
✅ Good: using an empty sandbox for maximum restriction
<iframe
src="https://example.com/widget"
sandbox="">
</iframe>
An empty sandbox attribute applies all restrictions — no scripts, no form submissions, no popups, no same-origin access, and more. This is the most secure option when the embedded content is purely static.
✅ Good: removing the sandbox when it provides no real benefit
<iframe
src="https://example.com/widget"
title="Example widget">
</iframe>
If you genuinely need both script execution and same-origin access, it's more honest to omit sandbox entirely and rely on other security measures, rather than including an attribute that provides a false sense of security.
The size attribute on an <input> element must be a whole number greater than zero, so size="0" is invalid.
size sets the visible width of a text field, counted in characters. It applies to the text, search, url, tel, email and password input types. The HTML standard requires a valid non-negative integer greater than zero, and browsers ignore a zero value and render the field at their default width of about 20 characters. Any value that parses to zero, such as 0 or 00, produces this error.
Templates and CMS search modules often write size="0" to mean "no fixed width" and leave the sizing to CSS. The attribute has no such meaning, so the zero only adds an error to the page.
Remove the attribute when CSS sets the width of the field, or set it to the number of characters that should be visible, such as size="30". The size attribute does not limit how much text the user can type; maxlength does that.
Invalid example
<form action="/search">
<label for="q">Search</label>
<input type="text" id="q" name="q" size="0">
</form>
Valid example
<form action="/search">
<label for="q">Search</label>
<input type="text" id="q" name="q" size="30">
</form>
The sizes attribute works together with srcset to help the browser choose the most appropriate image source for the current layout. It accepts a comma-separated list of entries, where each entry is an optional media condition followed by a CSS length value (called a "source size value"). The browser evaluates these entries to determine the intended display width of the image before it downloads it. Valid length values include viewport-relative units like 100vw, absolute units like 472px, or calc() expressions like calc(100vw - 2rem).
The value auto was not part of the original HTML specification for the sizes attribute. However, the sizes="auto" value has been added to the HTML living standard specifically for use with lazy-loaded images (loading="lazy"). When both loading="lazy" and sizes="auto" are present, the browser can defer size calculation until layout time, since the image won't be fetched immediately anyway. Some validators may not yet recognize this newer addition, or the error may appear because auto is being used without loading="lazy", or combined incorrectly with other size entries like sizes="auto, 100vw".
This validation error matters for several reasons. First, if the browser doesn't understand the sizes value, it may fall back to a default of 100vw, which could cause it to download a larger image than necessary, hurting performance. Second, malformed attribute values can lead to unpredictable behavior across different browsers. Third, standards compliance ensures your markup works reliably now and in the future.
How to Fix
You have a few options depending on your situation:
Replace
autowith a valid CSS length. If you know the intended display size of the image, specify it directly. This is the most broadly compatible approach.Use
sizes="auto"only withloading="lazy". If you want the browser to automatically determine the size, ensure you also includeloading="lazy"and awidthattribute on the image. Note that some validators may still flag this until they update their rules.Remove
autofrom a comma-separated list. If you have something likesizes="auto, (max-width: 600px) 100vw, 50vw", remove theautoentry entirely.
Examples
Incorrect: Using auto without lazy loading
This triggers the validation error because auto is not a valid CSS length in the traditional sizes syntax.
<img
src="image.jpg"
srcset="image-small.jpg 300w, image-medium.jpg 600w, image-large.jpg 1000w"
sizes="auto, 100vw"
alt="A scenic mountain landscape"
>
Fixed: Using a valid CSS length value
Replace auto with a concrete size or a set of media-conditioned sizes.
<img
src="image.jpg"
srcset="image-small.jpg 300w, image-medium.jpg 600w, image-large.jpg 1000w"
sizes="(max-width: 472px) 100vw, 472px"
alt="A scenic mountain landscape"
>
In this example, when the viewport is 472 pixels wide or smaller, the image takes up the full viewport width (100vw). For wider viewports, the browser knows the image will display at 472px wide and selects the best source from srcset accordingly.
Fixed: Using auto with lazy loading
If you want the browser to determine the display size automatically, pair sizes="auto" with loading="lazy" and explicit dimensions.
<img
src="image.jpg"
srcset="image-small.jpg 300w, image-medium.jpg 600w, image-large.jpg 1000w"
sizes="auto"
width="600"
height="400"
loading="lazy"
alt="A scenic mountain landscape"
>
The width and height attributes help the browser reserve the correct space in the layout, and loading="lazy" allows the browser to defer both loading and size calculation until the image is near the viewport.
Fixed: Using calc() for dynamic sizing
If your image sits inside a container with padding, you can use calc() for a precise size hint.
<img
src="image.jpg"
srcset="image-small.jpg 300w, image-medium.jpg 600w, image-large.jpg 1000w"
sizes="calc(100vw - 2rem)"
alt="A scenic mountain landscape"
>
The value of the sizes attribute on an <img> starts with a literal " character, which can't begin a media condition or a CSS length.
sizes holds a comma-separated list of source sizes. Each one is an optional media condition followed by a length, as in (max-width: 600px) 100vw, and the last one is usually a plain length such as 600px. Lazy-loaded images can also start the list with auto. The quotes around an attribute value are HTML syntax, not part of the value. When an extra " ends up inside it, the validator tries to read the entry as a length, finds the quote where it expects a digit or a minus sign, and rejects the value.
The stray quote usually comes from one of two mistakes. In the first, the quotes around the value were HTML-encoded as ", often by a plugin or template that escaped markup a second time. " can't delimit an attribute, so the parser reads sizes="(max-width: as an unquoted value that stops at the first space. The rest of the list turns into stray attributes such as 600px) and 100vw,, which the validator reports separately, and the bad value in this message is only the first word, such as "(max-width: or "auto,. In the second, the value is wrapped in two sets of quotes, as in sizes='"100vw"', and the whole list is the bad value.
Browsers drop a sizes value they can't parse and fall back to 100vw. They then pick the srcset candidate meant for a full-width layout, which is often a larger file than the image slot needs.
The cause rarely affects sizes alone. If width, height or srcset on the same <img> also report a stray ", fix the code that writes the tag instead of editing each attribute.
Invalid example
<img
src="logo-600.png"
alt="Company logo"
srcset="logo-600.png 600w, logo-1200.png 1200w"
sizes="(max-width: 600px) 100vw, 600px">
Valid example
<img
src="logo-600.png"
alt="Company logo"
srcset="logo-600.png 600w, logo-1200.png 1200w"
sizes="(max-width: 600px) 100vw, 600px">
A sizes attribute on an <img> element contains a media condition where a number is missing its CSS unit (like px, em, or rem).
The sizes attribute tells the browser how wide an image will be displayed at different viewport sizes, so it can pick the best source from a srcset. Each entry in sizes is a media condition paired with a length value. The media conditions follow standard CSS media query syntax, which means all non-zero numeric values must include a unit.
A common mistake is writing something like (max-width: 600) instead of (max-width: 600px). In CSS, bare numbers without units are invalid except for 0, which doesn't need a unit because zero pixels, zero ems, and zero rems are all the same thing.
Example with the error
<img
src="photo.jpg"
srcset="photo-480.jpg 480w, photo-800.jpg 800w"
sizes="(max-width: 600) 480px, 800px"
alt="A sunset over the ocean">
The media condition (max-width: 600) is missing a unit after 600.
Fixed example
<img
src="photo.jpg"
srcset="photo-480.jpg 480w, photo-800.jpg 800w"
sizes="(max-width: 600px) 480px, 800px"
alt="A sunset over the ocean">
Adding px (or whichever unit is appropriate) to the number in the media condition resolves the error. This applies to every numeric value in the media condition, not just the length that follows it. For example, (min-width: 40em) 50vw, 100vw is also valid.
The sizes attribute tells the browser how wide an image will be displayed under different viewport conditions, allowing it to choose the best candidate from srcset before the page layout is calculated. Its value is a comma-separated list where each entry (except optionally the last) pairs a media condition with a CSS length. The final entry can be a bare length that serves as the default fallback. The full syntax looks like this:
(media-condition) length, (media-condition) length, fallback-length
Media conditions use the same grammar as CSS media queries. They must be enclosed in parentheses and can use logical operators like and, or, and not to combine sub-expressions. The slot size (length) that follows each condition must use a valid CSS length unit such as px, em, rem, vw, vh, vmin, vmax, or ch. Percentages are not valid in sizes slot lengths, and unitless numbers (other than 0) are also invalid.
This error matters for several reasons. First, if the browser cannot parse the sizes value, it falls back to a default of 100vw, which may cause it to download an unnecessarily large image — hurting performance and wasting bandwidth. Second, an invalid sizes attribute signals a misunderstanding of responsive image markup that could lead to layout or rendering issues. Third, standards-compliant HTML ensures consistent behavior across all browsers.
Common Parse Errors
Here are the most frequent mistakes that trigger this validation error:
- Missing parentheses around the media condition. Writing
min-width: 600pxinstead of(min-width: 600px). - Missing slot size after a condition. Each media condition must be followed by a length value, e.g.,
(min-width: 600px) 50vw. Writing(min-width: 600px), 100vwwithout a slot size after the condition is invalid — the browser interprets(min-width: 600px)alone as the entry. - Using percentages as slot sizes. Values like
50%are not allowed; use viewport-relative units like50vwinstead. - Unitless numbers. A slot size of
300is invalid; it must be300pxor another valid length. - Trailing or extra commas. A trailing comma after the last entry or double commas between entries will cause a parse error.
- Mixing up range syntax. Modern media query range syntax like
(width >= 600px)is valid, but hybrid forms like(min-width <= 600px)are not. Use either the traditional(min-width: 600px)or the range form(width >= 600px). - Invalid tokens or typos. Misspelled feature names (e.g.,
min-widht) or unsupported tokens will break parsing.
How to Fix
- Wrap every media condition in parentheses. Even simple conditions need them:
(min-width: 600px). - Follow each condition with a valid length. For example,
(min-width: 600px) 50vw. - End with a fallback length. The last item should be a bare length with no media condition, like
100vw. - Use valid CSS length units for slot sizes —
px,em,rem,vw,vh, etc. Never use%. - Ensure your
srcsetuseswdescriptors that match the intrinsic pixel widths of the image files, sincesizesonly works with width descriptors.
Examples
Incorrect: missing parentheses and missing slot size
The media condition lacks parentheses, and there is no slot size telling the browser how wide the image will be when the condition matches.
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w"
sizes="min-width: 600px, 100vw"
alt="A mountain landscape">
Correct: parentheses and slot size added
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w"
sizes="(min-width: 600px) 50vw, 100vw"
alt="A mountain landscape">
Incorrect: percentage used as slot size
<img
src="banner-1200.jpg"
srcset="banner-600.jpg 600w, banner-1200.jpg 1200w"
sizes="(min-width: 768px) 50%, 100%"
alt="Promotional banner">
Correct: viewport units instead of percentages
<img
src="banner-1200.jpg"
srcset="banner-600.jpg 600w, banner-1200.jpg 1200w"
sizes="(min-width: 768px) 50vw, 100vw"
alt="Promotional banner">
Incorrect: trailing comma
<img
src="icon-256.png"
srcset="icon-128.png 128w, icon-256.png 256w"
sizes="(min-width: 1024px) 128px, 64px,"
alt="App icon">
Correct: trailing comma removed
<img
src="icon-256.png"
srcset="icon-128.png 128w, icon-256.png 256w"
sizes="(min-width: 1024px) 128px, 64px"
alt="App icon">
Incorrect: invalid range syntax mixing traditional and modern forms
<img
src="hero-1600.jpg"
srcset="hero-800.jpg 800w, hero-1600.jpg 1600w"
sizes="(min-width <= 600px) 100vw, 50vw"
alt="Hero image">
Correct: using proper range syntax
<img
src="hero-1600.jpg"
srcset="hero-800.jpg 800w, hero-1600.jpg 1600w"
sizes="(width <= 600px) 100vw, 50vw"
alt="Hero image">
Multiple conditions with a fallback
This example shows a fully valid sizes attribute with several breakpoints, combining traditional and modern range syntax across entries.
<img
src="article-1200.jpg"
srcset="article-400.jpg 400w, article-800.jpg 800w, article-1200.jpg 1200w"
sizes="(min-width: 1200px) 33vw, (min-width: 768px) 50vw, 100vw"
alt="Article thumbnail">
Using calc() in slot sizes
You can use calc() for more precise slot sizes. This is fully valid in the sizes attribute.
<img
src="card-800.jpg"
srcset="card-400.jpg 400w, card-800.jpg 800w"
sizes="(min-width: 960px) calc(33.33vw - 2rem), calc(100vw - 2rem)"
alt="Product card">
The sizes attribute works alongside srcset to tell the browser how wide an image will be displayed at various viewport sizes, so the browser can choose the most appropriate image source before the page layout is computed. The attribute value is a comma-separated list where each entry consists of an optional media condition followed by a source size value (a CSS length). The final entry in the list acts as the default size and should not include a media condition.
When the browser parses the sizes attribute and encounters an empty entry — meaning there is nothing meaningful between two commas or after a trailing comma — it cannot resolve that entry to a valid source size. The HTML living standard's parsing algorithm treats this as an error. While most browsers will silently ignore the empty entry and still render the image, the malformed attribute can lead to unexpected behavior and indicates a code quality issue that should be addressed.
Common causes of this error include:
- A trailing comma at the end of the
sizesvalue (e.g.,"100vw, 50vw, "). - Double commas in the middle of the list (e.g.,
"100vw, , 50vw"). - Dynamically generated values where a template or CMS outputs a comma even when a size entry is conditionally omitted.
Fixing the issue is straightforward: ensure every comma in the list separates two valid source size entries, and that the list neither begins nor ends with a comma.
Examples
Trailing comma (invalid)
The most common cause — a comma after the last entry creates an empty source size:
<img
src="photo.jpg"
alt="A mountain landscape"
sizes="(min-width: 1200px) 800px, (min-width: 600px) 400px, 100vw, "
srcset="photo-800.jpg 800w, photo-400.jpg 400w, photo-200.jpg 200w">
Trailing comma fixed
Remove the trailing comma so the list ends with a valid entry:
<img
src="photo.jpg"
alt="A mountain landscape"
sizes="(min-width: 1200px) 800px, (min-width: 600px) 400px, 100vw"
srcset="photo-800.jpg 800w, photo-400.jpg 400w, photo-200.jpg 200w">
Double comma in the middle (invalid)
A double comma creates an empty entry between two valid sizes:
<img
src="banner.jpg"
alt="Promotional banner"
sizes="(min-width: 1024px) 960px, , 100vw"
srcset="banner-960.jpg 960w, banner-480.jpg 480w">
Double comma fixed
Remove the extra comma so each entry is separated by exactly one comma:
<img
src="banner.jpg"
alt="Promotional banner"
sizes="(min-width: 1024px) 960px, 100vw"
srcset="banner-960.jpg 960w, banner-480.jpg 480w">
Dynamically generated sizes with an empty entry (invalid)
Templates or CMS platforms sometimes output commas for entries that are conditionally empty:
<img
src="hero.jpg"
alt="Hero image"
sizes="(min-width: 1400px) 1200px, , (min-width: 768px) 700px, 100vw"
srcset="hero-1200.jpg 1200w, hero-700.jpg 700w, hero-350.jpg 350w">
Dynamically generated sizes fixed
Ensure the template logic only outputs a comma when a valid entry follows:
<img
src="hero.jpg"
alt="Hero image"
sizes="(min-width: 1400px) 1200px, (min-width: 768px) 700px, 100vw"
srcset="hero-1200.jpg 1200w, hero-700.jpg 700w, hero-350.jpg 350w">
If your sizes attribute is built dynamically, consider filtering out empty values before joining them with commas, or trimming trailing commas from the final output. A well-formed sizes attribute should always consist of one or more valid entries separated by single commas, with the last entry serving as the default source size (typically something like 100vw).
The sizes and srcset attributes work together to enable responsive images, but they serve distinct roles and use different syntax. The srcset attribute lists available image files along with their intrinsic widths using the w descriptor (e.g., 800w means the image file is 800 pixels wide). The sizes attribute, on the other hand, tells the browser how wide the image will actually be rendered in the layout, using standard CSS length units. The browser combines this information — knowing which files are available and how large the image will appear — to choose the most efficient file to download.
A common mistake is mixing up these two syntaxes, typically by copying a width descriptor like 860w from srcset and placing it into sizes. Since w is not a CSS unit, the validator rejects it. This matters because an invalid sizes value prevents the browser from correctly calculating which image source to use, potentially causing it to download an unnecessarily large image (wasting bandwidth) or a too-small image (resulting in poor quality).
How the sizes attribute works
The sizes attribute accepts a comma-separated list of media conditions paired with CSS lengths, plus an optional default length at the end. Each entry follows the pattern (media-condition) length. The browser evaluates the conditions in order and uses the length from the first matching condition. If none match, it uses the final default value.
Valid CSS length units include px, em, rem, vw, vh, ch, cm, mm, in, pt, pc, and CSS calc() expressions. You can combine units with calc() for more precise sizing — for example, calc(100vw - 2rem).
Examples
❌ Incorrect: using w in sizes
This triggers the validation error because 860w is a srcset width descriptor, not a CSS length:
<img
alt="A landscape photo"
sizes="860w"
srcset="photo-small.jpg 430w, photo-large.jpg 860w"
src="photo-large.jpg">
✅ Correct: using px in sizes
Replace the w value with a CSS length that reflects the image's actual display size:
<img
alt="A landscape photo"
sizes="860px"
srcset="photo-small.jpg 430w, photo-large.jpg 860w"
src="photo-large.jpg">
✅ Correct: responsive sizes with media conditions
Use media conditions to specify different display sizes at different viewport widths:
<img
alt="A landscape photo"
sizes="(min-width: 1024px) 860px, (min-width: 568px) 430px, 100vw"
srcset="photo-small.jpg 430w, photo-large.jpg 860w"
src="photo-large.jpg">
This tells the browser:
- On viewports 1024px and wider, the image displays at 860px wide.
- On viewports 568px and wider, the image displays at 430px wide.
- On smaller viewports, the image fills the full viewport width (
100vw).
✅ Correct: using calc() in sizes
When the image width depends on padding or margins, calc() provides precise sizing:
<img
alt="A landscape photo"
sizes="(min-width: 768px) calc(50vw - 2rem), calc(100vw - 1rem)"
srcset="photo-small.jpg 400w, photo-medium.jpg 800w, photo-large.jpg 1200w"
src="photo-medium.jpg">
Key takeaways
- The
wdescriptor belongs only insrcset, where it describes the intrinsic width of each image file. - The
sizesattribute uses CSS length units (px,vw,em,calc(), etc.) to describe how wide the image will appear on screen. - If your image always displays at a fixed width, a simple value like
sizes="300px"is sufficient. - If your image width varies by viewport, use media conditions with appropriate CSS lengths to give the browser the information it needs to select the best source.
How the sizes Attribute Works
The sizes attribute works alongside srcset to enable responsive images. When you provide srcset with width descriptors (e.g., 400w, 800w), the browser needs to know how wide the image slot will actually be on screen so it can pick the best candidate. That's what sizes provides — a comma-separated list of size descriptors that tell the browser the rendered width of the image under various viewport conditions.
Each entry in the list follows this pattern:
- Optional media condition followed by a CSS length:
(max-width: 600px) 100vw - A final fallback length with no media condition:
33vw
The browser evaluates media conditions from left to right and uses the length from the first matching condition. If no condition matches, the fallback is used.
Why This Error Occurs
The validator checks that every length token in sizes uses one of the recognized CSS absolute or relative length units: em, ex, ch, rem, cap, ic, vw, vh, vmin, vmax, cm, mm, q, in, pc, pt, px, and their small/large/dynamic viewport variants (svw, lvw, dvw, svh, lvh, dvh, svi, lvi, dvi, svb, lvb, dvb, svmin, lvmin, dvmin, svmax, lvmax, dvmax).
Percentages (%) are not allowed. This is a common point of confusion — while % is valid in most CSS contexts, the sizes attribute explicitly forbids it because a percentage would be ambiguous (percentage of what?). The vw unit is typically the correct replacement when you want to express a fraction of the viewport width.
Here are the most common mistakes that trigger this error:
- Missing units:
sizes="100"— a bare number has no meaning without a unit. - Using percentages:
sizes="50%"— use50vwinstead. - Typos in unit names:
100pxx,100vws,50 vw(with a space between number and unit). - Multiple lengths in a single entry:
sizes="(min-width: 800px) 50vw 400px"— each entry must contain exactly one length. - Using
calc()incorrectly: Whilecalc()is valid insizes, the expressions inside it must also use valid units.
Why It Matters
When the sizes value is malformed, browsers fall back to a default of 100vw, which means every image is treated as if it spans the full viewport width. This defeats the purpose of responsive images — the browser may download unnecessarily large files on small screens, wasting bandwidth and slowing page loads. Valid sizes values are essential for proper image optimization.
Additionally, invalid HTML can cause unpredictable behavior across different browsers and versions. Standards-compliant markup ensures consistent rendering and forward compatibility.
How to Fix It
- Find the position indicated in the error message (the "at Z" part) — this tells you exactly where in the
sizesstring the invalid token was found. - Check for bare numbers and add the appropriate unit (
px,vw,em, etc.). - Replace
%withvwif you intended a percentage of the viewport width. - Fix any typos in unit names.
- Ensure each comma-separated entry has exactly one length, optionally preceded by a media condition in parentheses.
- Verify there's no space between the number and its unit —
100vwis correct,100 vwis not.
Examples
❌ Bare number without a unit
<img
src="photo-400.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w"
sizes="(max-width: 600px) 100, 400"
alt="A landscape photo">
✅ Fixed: add vw and px units
<img
src="photo-400.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w"
sizes="(max-width: 600px) 100vw, 400px"
alt="A landscape photo">
❌ Using invalid percentage
<img
src="banner-800.jpg"
srcset="banner-800.jpg 800w, banner-1600.jpg 1600w"
sizes="(max-width: 700px) 100%, 80%"
alt="Promotional banner">
✅ Fixed: replace % with vw
<img
src="banner-800.jpg"
srcset="banner-800.jpg 800w, banner-1600.jpg 1600w"
sizes="(max-width: 700px) 100vw, 80vw"
alt="Promotional banner">
❌ Multiple lengths in one entry
<img
src="hero-640.jpg"
srcset="hero-640.jpg 640w, hero-1280.jpg 1280w"
sizes="(min-width: 800px) 50vw 400px, 100vw"
alt="Hero image">
✅ Fixed: one length per entry, separated by commas
<img
src="hero-640.jpg"
srcset="hero-640.jpg 640w, hero-1280.jpg 1280w"
sizes="(min-width: 800px) 50vw, 100vw"
alt="Hero image">
❌ Typo in unit name
<img
src="thumb-320.jpg"
srcset="thumb-320.jpg 320w, thumb-640.jpg 640w"
sizes="320pxx"
alt="Thumbnail">
✅ Fixed: correct the unit
<img
src="thumb-320.jpg"
srcset="thumb-320.jpg 320w, thumb-640.jpg 640w"
sizes="320px"
alt="Thumbnail">
✅ Multiple media conditions with a fallback
<img
src="photo-640.jpg"
srcset="photo-640.jpg 640w, photo-960.jpg 960w, photo-1280.jpg 1280w"
sizes="(min-width: 1200px) 800px, (min-width: 800px) 60vw, 90vw"
alt="Landscape photo">
✅ Using calc() with valid units
<img
src="article-img-400.jpg"
srcset="article-img-400.jpg 400w, article-img-800.jpg 800w"
sizes="(min-width: 960px) calc(50vw - 2rem), 100vw"
alt="Article illustration">
The calc() function is valid inside sizes and is useful when the image width depends on a combination of viewport size and fixed spacing like padding or margins. Just make sure every value inside calc() also uses valid units.
The sizes attribute tells the browser how wide an image will be displayed at different viewport sizes, so it can choose the best candidate from srcset. It only applies when srcset uses width descriptors (e.g., 480w, 800w). The value is a comma-separated list where:
- Each entry (except the last) is a media condition in parentheses followed by a CSS length — for example,
(min-width: 800px) 50vw. - The final entry is a fallback length with no media condition — for example,
100vw.
The browser evaluates the media conditions from left to right and uses the length from the first one that matches. If none match, it uses the fallback.
The media condition syntax mirrors CSS media queries but without the @media keyword. You can use logical operators like and, or, and not, and features like min-width, max-width, orientation, etc.
Why This Error Occurs
The validator parses the sizes value according to the HTML living standard and CSS Media Queries specification. A parse error is triggered when the value doesn't conform to the expected grammar. Common causes include:
- Missing parentheses around the media condition:
min-width: 600px 50vwinstead of(min-width: 600px) 50vw. - Missing length after a media condition:
(min-width: 800px)with no length following it. - Invalid or missing units on the length:
50instead of50vw,50px, or50rem. - Trailing commas or extra separators:
(min-width: 600px) 50vw, , 100vw. - Invalid media feature syntax: typos like
(minwidth: 600px)or using unsupported tokens. - Using
sizeswith pixel-density descriptors: whensrcsetuses1x,2xinstead of width descriptors, thesizesattribute is meaningless and can confuse validators.
Why It Matters
- Browser image selection: Browsers rely on a correctly parsed
sizesvalue to pick the optimal image fromsrcset. A malformed value causes the browser to fall back to a default size (typically100vw), which can result in downloading unnecessarily large images on small screens or blurry images on large screens. - Standards compliance: Invalid
sizesvalues violate the HTML specification and may behave unpredictably across different browsers. - Performance: Correct
sizesvalues are essential for responsive image optimization. Without them, you lose the bandwidth savings thatsrcsetwith width descriptors is designed to provide.
How to Fix It
- Wrap every media condition in parentheses:
(min-width: 600px), notmin-width: 600px. - Always include a valid CSS length after each condition:
(min-width: 600px) 50vw, not just(min-width: 600px). - End with a fallback length that has no condition:
100vw. - Use valid CSS length units:
vw,px,em,rem, orcalc()expressions. - Remove trailing or duplicate commas.
- Omit
sizesentirely if yoursrcsetuses pixel-density descriptors (1x,2x).
Examples
Incorrect: missing parentheses around the media condition
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w"
sizes="min-width: 600px 50vw, 100vw"
alt="A landscape photo">
Correct: parentheses added
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w"
sizes="(min-width: 600px) 50vw, 100vw"
alt="A landscape photo">
Incorrect: missing length after the media condition
<img
src="banner-800.jpg"
srcset="banner-400.jpg 400w, banner-800.jpg 800w"
sizes="(min-width: 700px), 100vw"
alt="A promotional banner">
The first entry (min-width: 700px) has no length value — the comma makes it look like a separate entry, but it's incomplete.
Correct: length added after the condition
<img
src="banner-800.jpg"
srcset="banner-400.jpg 400w, banner-800.jpg 800w"
sizes="(min-width: 700px) 60vw, 100vw"
alt="A promotional banner">
Incorrect: using sizes with pixel-density descriptors
<img
src="avatar.jpg"
srcset="avatar@1x.jpg 1x, avatar@2x.jpg 2x"
sizes="(min-width: 600px) 80px, 40px"
alt="User avatar">
The sizes attribute is only meaningful with width descriptors (w). When srcset uses density descriptors (1x, 2x), omit sizes.
Correct: sizes removed for density descriptors
<img
src="avatar.jpg"
srcset="avatar@1x.jpg 1x, avatar@2x.jpg 2x"
alt="User avatar">
Incorrect: trailing comma
<img
src="hero-800.jpg"
srcset="hero-400.jpg 400w, hero-800.jpg 800w"
sizes="(min-width: 800px) 800px, 100vw,"
alt="Hero image">
Correct: trailing comma removed
<img
src="hero-800.jpg"
srcset="hero-400.jpg 400w, hero-800.jpg 800w"
sizes="(min-width: 800px) 800px, 100vw"
alt="Hero image">
Using sizes on a <source> inside <picture>
<picture>
<source
type="image/webp"
srcset="hero-480.webp 480w, hero-800.webp 800w, hero-1200.webp 1200w"
sizes="(min-width: 1200px) 1200px, (min-width: 800px) 800px, 100vw">
<img
src="hero-800.jpg"
srcset="hero-480.jpg 480w, hero-800.jpg 800w, hero-1200.jpg 1200w"
sizes="(min-width: 1200px) 1200px, (min-width: 800px) 800px, 100vw"
alt="Hero image">
</picture>
Using compound media conditions
You can combine conditions with and:
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1200.jpg 1200w"
sizes="(min-width: 900px) and (orientation: landscape) 50vw, 100vw"
alt="A sample photo">
Full valid document
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Responsive Image Example</title>
</head>
<body>
<img
src="pic-800.jpg"
srcset="pic-400.jpg 400w, pic-800.jpg 800w"
sizes="(min-width: 600px) 50vw, 100vw"
alt="A picture demonstrating valid sizes usage">
</body>
</html>
The sizes attribute on a <source> element contains a media condition or length value with malformed syntax, likely a missing or misspelled CSS function name where one is expected.
The sizes attribute tells the browser how wide an image will be displayed under various layout conditions. Its value is a comma-separated list of entries, each consisting of an optional media condition and a length. The length portion must be a valid CSS length, which can include plain values like 50vw or 100px, but also CSS math functions like calc(), min(), max(), and clamp().
This error fires when the validator's parser hits a spot in the sizes value where it expects a CSS function name but finds something else. Common causes:
- A missing function name, such as writing
(100vw - 2rem)instead ofcalc(100vw - 2rem). Parenthesized math expressions require an explicitcalc()wrapper. - A typo in a function name, like
clac(...)instead ofcalc(...). - Nesting errors or misplaced parentheses that confuse the parser about where a function should begin.
Invalid example
<picture>
<source
srcset="image-800.jpg 800w, image-1200.jpg 1200w"
sizes="(min-width: 768px) (100vw - 4rem), 100vw"
type="image/jpeg">
<img src="image-800.jpg" alt="A mountain landscape">
</picture>
The expression (100vw - 4rem) is not a valid CSS length on its own. The validator expects a function name before the opening parenthesis.
Fixed example
<picture>
<source
srcset="image-800.jpg 800w, image-1200.jpg 1200w"
sizes="(min-width: 768px) calc(100vw - 4rem), 100vw"
type="image/jpeg">
<img src="image-800.jpg" alt="A mountain landscape">
</picture>
Wrapping the arithmetic in calc() makes it a valid CSS length expression and resolves the validation error.
The sizes attribute tells the browser how wide an image will be displayed at various viewport sizes, so it can choose the best candidate from srcset before the CSS has loaded. Each entry in the sizes list is either a media condition paired with a CSS length, or a bare fallback length at the end. The HTML specification requires these lengths to be valid CSS <length> values, which means a number followed by a recognized unit. The full list of accepted units includes px, em, ex, ch, rem, vw, vh, vmin, vmax, cm, mm, in, pt, pc, and newer viewport units like svw, lvw, dvw, svh, lvh, dvh, and others.
The calc() function is also permitted, which lets you combine units — for example, calc(100vw - 2rem).
Why this matters
The sizes attribute is parsed before layout occurs, meaning the browser relies on it being syntactically correct to make smart download decisions. An invalid value forces the browser to fall back to a default size (typically 100vw), which can lead to downloading images that are far too large or too small. Beyond performance, an invalid sizes value violates the HTML specification, and some browsers may handle the malformed input inconsistently, leading to unpredictable behavior across devices.
Common mistakes
- Missing unit entirely: Writing
800instead of800px. Bare numbers without units are not valid CSS lengths (the only exception in CSS is0, but even0should have a unit insizesfor clarity). - Using percentages: Writing
50%instead of50vw. Percentages are not allowed insizesbecause the browser hasn't performed layout yet and doesn't know what the percentage would be relative to. Use viewport units likevwinstead. - Typos or extra characters: A stray character, misplaced comma, or missing whitespace can shift the parser's position and cause it to find unexpected tokens where it expects a unit.
- Using
autoon<source>: Theautokeyword forsizesis only valid on<img>elements (and requires theloading="lazy"attribute). Using it on<source>will trigger a validation error.
How to fix it
- Find the position indicated in the error message ("at Z") to locate the problematic value.
- If the value is a bare number, append the correct unit (e.g., change
600to600px). - If the value uses
%, replace it with a viewport-relative unit likevw. - Ensure commas separate each media-condition/length pair, and that the list ends with a fallback length.
Examples
Adding a missing unit
The value 800 in the sizes attribute is not a valid CSS length because it has no unit.
<!-- ❌ Invalid: "800" is missing a unit -->
<img
src="hero-800.jpg"
srcset="hero-800.jpg 800w, hero-1200.jpg 1200w"
sizes="(min-width: 900px) 800, 100vw"
alt="Hero image">
<!-- ✅ Valid: "800px" has a proper unit -->
<img
src="hero-800.jpg"
srcset="hero-800.jpg 800w, hero-1200.jpg 1200w"
sizes="(min-width: 900px) 800px, 100vw"
alt="Hero image">
Replacing a percentage with a viewport unit
Percentages are not permitted in sizes. Use vw to express a width relative to the viewport.
<!-- ❌ Invalid: "50%" is not an allowed unit in sizes -->
<img
src="card-600.jpg"
srcset="card-600.jpg 600w, card-900.jpg 900w"
sizes="50%"
alt="Product card">
<!-- ✅ Valid: "50vw" means 50% of the viewport width -->
<img
src="card-600.jpg"
srcset="card-600.jpg 600w, card-900.jpg 900w"
sizes="50vw"
alt="Product card">
Fixing the issue on a <source> element
The same rules apply to <source> elements inside <picture>. Every length value needs a valid unit.
<!-- ❌ Invalid: "600" on <source> is missing a unit -->
<picture>
<source
type="image/webp"
srcset="hero-600.webp 600w, hero-1200.webp 1200w"
sizes="(min-width: 768px) 600, 100vw">
<img
src="hero-600.jpg"
srcset="hero-600.jpg 600w, hero-1200.jpg 1200w"
sizes="(min-width: 768px) 600px, 100vw"
alt="Hero image">
</picture>
<!-- ✅ Valid: both <source> and <img> use proper units -->
<picture>
<source
type="image/webp"
srcset="hero-600.webp 600w, hero-1200.webp 1200w"
sizes="(min-width: 768px) 600px, 100vw">
<img
src="hero-600.jpg"
srcset="hero-600.jpg 600w, hero-1200.jpg 1200w"
sizes="(min-width: 768px) 600px, 100vw"
alt="Hero image">
</picture>
Using calc() for mixed-unit sizes
You can use calc() to combine different units, which is especially useful when accounting for padding or margins.
<img
src="article-800.jpg"
srcset="article-800.jpg 800w, article-1200.jpg 1200w"
sizes="(min-width: 1024px) calc(100vw - 4rem), 100vw"
alt="Article image">
Multiple slots with different conditions
A well-formed sizes attribute with several media conditions, ending with a unitless-condition fallback length:
<picture>
<source
type="image/avif"
srcset="banner-480.avif 480w, banner-960.avif 960w, banner-1440.avif 1440w"
sizes="(min-width: 1200px) 960px, (min-width: 600px) 80vw, 100vw">
<img
src="banner-480.jpg"
srcset="banner-480.jpg 480w, banner-960.jpg 960w, banner-1440.jpg 1440w"
sizes="(min-width: 1200px) 960px, (min-width: 600px) 80vw, 100vw"
alt="Responsive banner">
</picture>
The general pattern is: sizes="(condition) length, (condition) length, fallback-length". Every length in that list — including the fallback — must be a valid CSS length with a unit or a calc() expression. If the validator error points to a specific character position, inspect that exact spot for a missing unit, a stray %, or malformed whitespace and replace it with one of the recognized units.
A sizes attribute on a <source> element contains a length value that is missing valid CSS units or uses an unrecognized unit.
The sizes attribute tells the browser how wide an image will be displayed at a given viewport condition. Each entry in the sizes list is either a media condition paired with a source size value, or a default source size value. The source size value must be a valid CSS length, which means it requires a recognized unit such as px, vw, em, or rem. Bare numbers without units, percentage values (%), or made-up units are not allowed.
A common mistake is writing a bare number like 300 instead of 300px, or using % instead of vw. The % unit is explicitly disallowed in sizes because the browser needs to resolve image widths before layout is complete, and percentage lengths depend on a containing block that may not be known yet. Use vw (viewport width) when you want a percentage-like relative size.
The sizes attribute applies to <source> elements inside a <picture>, and also to <img> elements directly.
Invalid example
<picture>
<source
srcset="image-480.jpg 480w, image-800.jpg 800w"
sizes="(max-width: 600px) 100%, 50%"
type="image/jpeg">
<img src="image-800.jpg" alt="A sample photo">
</picture>
The validator rejects 100% and 50% because % is not a permitted unit in sizes.
Fixed example
<picture>
<source
srcset="image-480.jpg 480w, image-800.jpg 800w"
sizes="(max-width: 600px) 100vw, 50vw"
type="image/jpeg">
<img src="image-800.jpg" alt="A sample photo">
</picture>
Replace % with vw, or use any other valid CSS absolute or relative length unit (px, em, rem, etc.). A calc() expression with valid units also works, for example calc(100vw - 2rem).
A URL follows a specific structure defined by RFC 3986. The general format is:
scheme://host/path?query#fragment
The # character serves as the delimiter that introduces the fragment portion of the URL. It may only appear once in this role. Once the parser encounters the first #, everything after it is treated as the fragment identifier. A second # within that fragment is an illegal character because the fragment production in the URL specification does not permit unescaped # characters.
This validation error commonly arises from:
- Duplicate
#characters — e.g., accidentally including two hash marks like/#?param=value#section. - Misplaced query strings — putting
?key=valueafter the#instead of before it. While this may work in some single-page application routers, it results in the query being part of the fragment, and adding another#after that creates an invalid URL. - Copy-paste errors — assembling URLs from multiple parts and inadvertently introducing an extra
#.
This matters for several reasons. Browsers may handle malformed URLs inconsistently — some may silently truncate or ignore part of the URL, while others may fail to load the resource entirely. The W3C validator flags this because it violates the HTML specification's requirement that the src attribute contain a valid URL. Invalid URLs can also cause issues with assistive technologies, link sharing, and automated tools that parse your HTML.
How to fix it
- Locate all
#characters in the URL and determine which one is the intended fragment delimiter. - Remove any duplicate
#characters that were added by mistake. - Move query parameters before the fragment — the
?queryportion must come before the#fragmentin a well-formed URL. - Percent-encode if needed — if a literal
#must appear as data within the fragment or query value (not as a delimiter), encode it as%23.
Examples
Incorrect: multiple # characters
The second # inside the fragment is illegal:
<iframe src="https://example.com/#?secret=123#abc"></iframe>
Correct: query before fragment
Move the query string before the # so the URL has a proper structure:
<iframe src="https://example.com/?secret=123#abc"></iframe>
Correct: single fragment, no query
If you only need a fragment identifier, use a single #:
<iframe src="https://example.com/#abc"></iframe>
Correct: percent-encoding a literal # in a value
If the fragment itself must contain a # as data (not as a delimiter), percent-encode it:
<iframe src="https://example.com/?secret=123#color=%23ff0000"></iframe>
Here, %23ff0000 represents the literal string #ff0000 within the fragment value, which is valid because the # is encoded.
Incorrect: hash-based routing with duplicate #
Some single-page app embed URLs use hash-based routing, which can lead to accidental double hashes:
<iframe src="https://app.example.com/#/dashboard#settings"></iframe>
Correct: use a single fragment for the route
Restructure the URL to use a single # with a combined path:
<iframe src="https://app.example.com/#/dashboard/settings"></iframe>
Or, if the application supports it, use standard path-based routing instead:
<iframe src="https://app.example.com/dashboard/settings"></iframe>
A space character in the src attribute of an iframe is not valid in a URL. Spaces must be percent-encoded as %20 to produce a legal URL.
URLs follow the syntax rules defined in RFC 3986, which does not allow literal space characters anywhere in a URI, including the query string portion (the part after ?). When the HTML validator encounters a raw space in a URL attribute like src, it flags the value as malformed.
This commonly happens when query parameter values contain readable text, or when a URL is copied from a browser's address bar where the browser displays decoded spaces for readability. The fix is to replace each space with %20.
Some developers use + instead of %20 for spaces in query strings. The + convention originates from the application/x-www-form-urlencoded format used in HTML form submissions, and many servers accept it. However, %20 is the correct encoding according to RFC 3986 and will pass W3C validation without issues.
HTML examples
Invalid: space in the query string
<iframe
src="https://example.com/embed?title=my page&lang=en"
width="600"
height="400">
</iframe>
Valid: space encoded as %20
<iframe
src="https://example.com/embed?title=my%20page&lang=en"
width="600"
height="400">
</iframe>
When the W3C HTML Validator reports "Bad value X for attribute src on element iframe: Illegal character in query: [ is not allowed", it means your URL contains unencoded square brackets in the query portion (everything after the ?). While most modern browsers will silently handle these characters and load the resource anyway, the URL does not conform to the URI syntax defined in RFC 3986, which the HTML specification requires.
According to RFC 3986, square brackets are reserved characters that have a specific purpose: they are only permitted in the host component of a URI to denote IPv6 addresses (e.g., http://[::1]/). Anywhere else in the URI — including the query string — they must be percent-encoded. The HTML living standard (WHATWG) requires that URLs in attributes like src, href, and action be valid URLs, which means they must follow these encoding rules.
Why this matters
- Standards compliance: Invalid URLs cause W3C validation failures, which can indicate deeper issues in your markup.
- Interoperability: While mainstream browsers are forgiving, some HTTP clients, proxies, CDNs, or web application firewalls may reject or mangle URLs with unencoded square brackets.
- Consistent behavior: Percent-encoding reserved characters guarantees that the URL is interpreted the same way everywhere — in browsers, server logs, link checkers, and automated tools.
- Copy-paste reliability: When users or tools copy a URL from your HTML source, an already-encoded URL is less likely to break during transmission through email clients, messaging apps, or other systems.
How to fix it
Replace every occurrence of [ with %5B and ] with %5D within the query string of the URL. If you're generating URLs server-side or in JavaScript, use the language's built-in URL encoding functions rather than doing manual find-and-replace:
- JavaScript:
encodeURIComponent()or theURL/URLSearchParamsAPIs - PHP:
urlencode()orhttp_build_query() - Python:
urllib.parse.urlencode()orurllib.parse.quote()
These functions will automatically encode square brackets and any other reserved characters.
Examples
❌ Invalid — unencoded square brackets in query string
<iframe src="https://example.com/embed?filter[status]=active&filter[type]=video"></iframe>
The validator flags [ and ] as illegal characters in the query component.
✅ Valid — square brackets percent-encoded
<iframe src="https://example.com/embed?filter%5Bstatus%5D=active&filter%5Btype%5D=video"></iframe>
Replacing [ with %5B and ] with %5D resolves the error. The server receives the exact same parameter values — most server-side frameworks (PHP, Rails, etc.) automatically decode percent-encoded characters before processing them.
❌ Invalid — square brackets in a timestamp parameter
<iframe src="https://example.com/report?time=[2024-01-01]"></iframe>
✅ Valid — timestamp parameter properly encoded
<iframe src="https://example.com/report?time=%5B2024-01-01%5D"></iframe>
Generating encoded URLs in JavaScript
If you're setting the src dynamically, let the browser handle encoding for you:
<iframe id="report-frame"></iframe>
<script>
const url = new URL("https://example.com/embed");
url.searchParams.set("filter[status]", "active");
url.searchParams.set("filter[type]", "video");
document.getElementById("report-frame").src = url.toString();
</script>
The URLSearchParams API automatically percent-encodes the brackets, producing a valid URL in the src attribute.
A note on other elements
This same rule applies to any HTML attribute that accepts a URL — including href on <a> elements, action on <form> elements, and src on <script> or <img> elements. Whenever you place a URL in HTML, ensure all reserved characters in the query string are properly percent-encoded.
Backslashes are not valid delimiters in URLs according to the URL Living Standard. While some browsers may silently normalize backslashes to forward slashes, this behavior is non-standard and should not be relied upon. Using backslashes in URLs can lead to broken images, unexpected behavior across different browsers, and failures in environments that strictly follow URL specifications (such as HTTP servers, CDNs, or validation tools).
This issue commonly arises when developers copy file paths directly from a Windows file system — where \ is the directory separator — and paste them into HTML src attributes. It can also happen when server-side code generates URLs using OS-level path functions instead of URL-building utilities.
Beyond standards compliance, this matters for several practical reasons:
- Cross-browser reliability: Not all browsers or HTTP clients normalize backslashes the same way.
- Server compatibility: Many web servers interpret backslashes literally, resulting in 404 errors.
- Portability: Code with backslash paths may work in local development on Windows but break when deployed to a Linux-based server.
To fix the issue, locate every backslash in the src attribute value and replace it with a forward slash. This applies to all URL contexts, not just img elements — though the validator specifically flags it here.
Examples
❌ Incorrect: backslashes in the src path
<img src="images\photos\landscape.jpg" alt="Mountain landscape">
<img src="https://example.com\img\small\photo.png" alt="Example image">
Both of these use backslashes as path delimiters, which triggers the validation error.
✅ Correct: forward slashes in the src path
<img src="images/photos/landscape.jpg" alt="Mountain landscape">
<img src="https://example.com/img/small/photo.png" alt="Example image">
Simply replacing \ with / resolves the issue and produces a valid, portable URL.
❌ Incorrect: mixed delimiters
<img src="assets/images\banner\hero.webp" alt="Hero banner">
Even a single backslash in an otherwise valid path will trigger this error.
✅ Correct: consistent forward slashes
<img src="assets/images/banner/hero.webp" alt="Hero banner">
Tips to avoid this issue
- Don't copy-paste Windows file paths directly into HTML. Always convert backslashes to forward slashes.
- Use your editor's find-and-replace to search for
\withinsrcattributes across your project. - If generating URLs in server-side code, use URL-building functions rather than file-system path functions. For example, in Node.js, use the
urlmodule or template literals with/instead ofpath.join(), which uses\on Windows. - Run the W3C validator regularly during development to catch issues like this before deployment.
A data: URI in the src attribute of an <img> element can't contain a raw <, so inline SVG markup in that URI needs its angle brackets written as %3C and %3E.
A data: URI puts the file itself inside the URL, and everything after the comma has to be made of URL characters. Angle brackets, spaces and double quotes aren't. The validator stops at the first illegal character, which in inline SVG is the < that opens the <svg> tag. The ta: in the message is just the end of data:. The validator quotes the scheme, not the spot where the bad character sits.
This markup often comes from lazy-loading scripts. An empty SVG with only width and height sits in src as a placeholder that reserves the image's box, while the real file waits in data-src or data-srcset. Browsers usually render the placeholder anyway, but the value is still an invalid URL.
Encoding only the angle brackets isn't enough: the validator then reports the first space. Write < as %3C, > as %3E and each space as %20, and use single quotes inside the SVG or encode double quotes as %22. Also remove the ;utf8 after the media type, or write it as ;charset=utf-8. Once the brackets are encoded, the validator rejects a parameter with no value. In JavaScript, encodeURIComponent() produces a valid string, and a base64-encoded SVG with ;base64 before the comma avoids the problem too.
Invalid example
<img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='300' height='200'></svg>" data-src="photo.jpg" alt="Product photo">
Valid example
<img src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='300'%20height='200'%3E%3C/svg%3E" data-src="photo.jpg" alt="Product photo">
A data: URI in the src attribute of an <img> element can't contain literal spaces, so an inline SVG in that URI needs every space written as %20.
The data: scheme, defined in RFC 2397, puts the file itself in the attribute value. The data after the comma may only contain URL characters, and a space isn't one of them. The ta: in the message is the end of data:. The validator quotes the scheme rather than the position of the space, so the space can be anywhere in the value.
Inline SVG is the usual cause. SVG markup needs a space between the element name and each attribute, as in <svg xmlns='...' width='300'>, and encoding the angle brackets as %3C and %3E leaves those spaces alone. A common case is an empty SVG with only width and height, used as a placeholder that holds the image's box until the real file loads.
Browsers usually render the image anyway, but the value is still an invalid URL. Replace every space with %20, or base64-encode the SVG and add ;base64 before the comma. In JavaScript, encodeURIComponent() converts the spaces to %20, along with the angle brackets and double quotes. If the SVG is large or reused, save it as a file and point src at that file.
Invalid example
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='300' height='200'/%3E" alt="">
Valid examples
<img src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20width='300'%20height='200'/%3E" alt="">
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMDAiIGhlaWdodD0iMjAwIi8+" alt="">
URLs follow strict syntax rules defined by RFC 3986. Within a URL's path segment, only a specific set of characters is allowed to appear literally. When a character falls outside this allowed set, it must be percent-encoded — represented as a % sign followed by two hexadecimal digits corresponding to the character's ASCII code. The W3C validator checks that every URL in your HTML conforms to these rules, and it flags any src value that contains raw illegal characters.
Characters that commonly trigger this error include:
| Character | Percent-encoded |
|---|---|
| (space) | %20 |
[ | %5B |
] | %5D |
{ | %7B |
} | %7D |
| | %7C |
^ | %5E |
` | %60 |
Other reserved characters like ?, #, @, !, $, &, ', (, ), *, +, ,, ;, and = also need encoding when used as literal data in a path segment rather than as URL delimiters. The % character itself must be encoded as %25 if it appears literally.
Why This Is a Problem
- Browser inconsistency: While many modern browsers silently fix malformed URLs, not all do. Some browsers, older user agents, or HTTP clients may fail to load the resource or interpret the URL differently, leading to broken images.
- Standards compliance: Invalid URLs violate the HTML specification, which requires that attribute values containing URLs conform to valid URL syntax.
- Interoperability: Servers, CDNs, proxies, and caching layers may handle illegal characters unpredictably, causing intermittent failures that are difficult to debug.
- Accessibility: If a URL is malformed and the image fails to load, users relying on assistive technologies may not receive the intended content, even when appropriate
alttext is provided.
How to Fix It
You have two main approaches:
- Percent-encode the illegal characters in the
srcvalue. Replace each offending character with its%XXequivalent. - Rename the file to use only URL-safe characters. Stick to lowercase letters, digits, hyphens (
-), underscores (_), and dots (.). This is the cleanest long-term solution.
If you're generating URLs programmatically, use your language's built-in URL encoding functions (e.g., encodeURIComponent() in JavaScript, urlencode() in PHP, or urllib.parse.quote() in Python).
Examples
Illegal characters in the filename
The square brackets in the src value are not allowed in a URL path segment:
<!-- ❌ Invalid: raw [ and ] in URL path -->
<img src="image[00].svg" alt="Company logo">
Fix by percent-encoding:
<!-- ✅ Valid: [ and ] are percent-encoded -->
<img src="image%5B00%5D.svg" alt="Company logo">
Fix by renaming the file:
<!-- ✅ Valid: filename uses only safe characters -->
<img src="image-00.svg" alt="Company logo">
Spaces in the filename
Spaces are one of the most common causes of this error:
<!-- ❌ Invalid: space in URL path -->
<img src="my photo.jpg" alt="Vacation photo">
<!-- ✅ Valid: space encoded as %20 -->
<img src="my%20photo.jpg" alt="Vacation photo">
<!-- ✅ Valid: filename uses a hyphen instead of a space -->
<img src="my-photo.jpg" alt="Vacation photo">
Curly braces in a template-like path
Sometimes filenames or paths contain curly braces from templating artifacts or naming conventions:
<!-- ❌ Invalid: raw { and } in URL path -->
<img src="icons/{home}.png" alt="Home icon">
<!-- ✅ Valid: curly braces percent-encoded -->
<img src="icons/%7Bhome%7D.png" alt="Home icon">
Best practice for file naming
The simplest way to avoid this error entirely is to adopt a consistent file naming convention that only uses URL-safe characters:
<!-- ✅ Valid: clean, URL-safe filenames -->
<img src="images/hero-banner-2024.webp" alt="Welcome banner">
<img src="photos/team_photo_01.jpg" alt="Our team">
Validate at scale.
Ship accessible websites, faster.
Automated HTML & accessibility validation for large sites. Check thousands of pages against WCAG guidelines and W3C standards in minutes, not days.
1K Weekly
1,000 monthly checks. Cancel anytime.
Get 1K Weekly →Join teams across 40+ countries