Can we place `<img>` inside `<h1>` according to web standards?
Asked Answered
C

5

67

Can we place <img> inside <h1> according to web standards? like this

<h1> Demo text <img src="anyimage.jpg"/> </h1>
Cockspur answered 22/10, 2009 at 6:56 Comment(0)
P
98

Yes, you can - the DTD says:

<!ELEMENT h1  %Inline;>
<!ENTITY % Inline "(#PCDATA | %inline; | %misc.inline;)*">
<!ENTITY % inline "a | %special; | %fontstyle; | %phrase; | %inline.forms;">
<!ENTITY % special "%special.pre; | object | img ">

That basically means h1 can contain %Inline, which is made of various things, including img

Prisilla answered 22/10, 2009 at 6:59 Comment(0)
S
54

Look who is using it: http://www.w3.org/

<h1 class="logo"><a tabindex="2" accesskey="1" href="/"><img src="/2008/site/images/logo-w3c-mobile-lg" width="90" height="53" alt="W3C" /></a> <span class="alt-logo">W3C</span></h1>
Stator answered 22/10, 2009 at 7:20 Comment(3)
Well, that might be wrong usage. When using screen reader it reads out loud: "W3C W3C". Because it reads out loud alt attribute and span element. I'm not sure but if span were defined with display: hidden it wouldn't read it. Good reading for ALT text is here.Cyclotron
I agree, responding to this late. But if it were 2018. I would set the alt equal to the empty string, " ". And keep the span with a screen-reader the only css.Dicks
@Dicks You mean something like <h1><img src="img.png" alt="" /><span class="screen-reader-text">My title</span></h1> Do search engines dock rankings based on hidden text like that?Suez
S
21

Yes, this is allowed. But don’t forget to set the alt attribute on the img!

Stallings answered 22/10, 2009 at 6:58 Comment(1)
+1 for mentioning alt. Basically when the image cannot be displayed, the alt text acts as the contents of the h1.Jolson
C
5

Yes and no.

You can place an image inside an h1 element, but not quite like that … the alt attribute is mandatory.

Charteris answered 22/10, 2009 at 6:58 Comment(0)
L
4

To summarize the other answers, it is W3C valid to use an <img> inside an <h1>.

Though to be completly valid you should add an alt attribute to your image, because it's mandatory. This attribute doesn't need to contain text. It's better letting it empty than repeating what is already written in the h1 tag.

In your case if the image is purely decorative it should be:

<h1>Demo text <img src="anyimage.jpg" alt=""/></h1>

More info on text alternatives for decorative images: https://www.w3.org/WAI/tutorials/images/decorative/

If the image has a particular meaning or contains a text different than the one in the h1, then use an appropriate alternative.

Lubricant answered 4/11, 2019 at 13:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.