Can I nest an image inside a link and vice versa?
In the example we did on webacademy we nested an image inside a link.
I personally can’t see that happening because if so there would be no “end tag”
Answer 543b5de980ff33443100130d
We can nest an image inside a link, yes. The reverse is not possible since images are void
tags with no content. They cannot be a parent element.
<a><img></a>
Stripped down this is the structure. We can even have multiple images or images and text or images with spans and text.
Anchor elements, as well as img and span elements are inline by default. If we wrap an image with an anchor element, the image becomes the anchor target. We can click the image anywhere and the link will work. If there is text as well, it too can be clicked.
What we cannot do is have another anchor inside an anchor. That would be invalid and could have some weird side effects. We should also not wrap a block level element with an anchor, since this goes against normal flow and is not recommended.
In the old days, before id
was introduced to HTML, an empty anchor tag would be used to anchor a page fragment:
<a name="fragment"></a>
This is very old and outdated by today’s standards but we still see this in present day HTML. Nowadays we just write an id on an element and hook that instead. Much neater, and way more powerful:
<div id="fragment"></div>
Both fragments are hooked the same way:
<a href="#fragment">Page fragment</a>
Very soon you will learn how to give an anchor dimensions, so I won’t go into that now. I think we’ve covered some of the basics, here. That’s a good start.
It’s a good idea to have either width
and height
attributes in the img tag, or give it a class/id and specify dimensions in the CSS. This way the browser creates a placeholder for the image while it downloads and goes on drawing the page. If no dimensions are given, the browser has to wait for the image to download before it can calculate the dimensions, really slowing down the page load and causing the load sequence to jump and morph.
<a href="http://www.codecademy.com"><img src="http://cdn-production.codecademy.com/assets/logo/logo--dark-blue-bf11002ce1caecdfb9fec8d3286b8a8d.svg" width="150" height="30" alt="codecademy"></a>
2 comments
Great response! I didn’t get to CSS yet so I don’t understand the second half, but the anchor explanation helped a lot, thank you!
This will all be commonplace in short order. Keep forging on…
Popular free courses
- Free course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner Friendly4 Lessons - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly11 Lessons - Free course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner Friendly6 Lessons