Computer >> Computer tutorials >  >> Programming >> HTML

How to Create HTML Image Links

Images are common components of any web page. They are also a great way to create a link to another page. By using a combination of anchor tags with an href attribute and image tags, we can create an image that works as a link between two pages. You can accomplish this by following the steps below: 

  1. Create a div element. This will hold our image element, our anchor tag and anything else we might want to use to describe the link. 
  2. Next, create an anchor tag. <a> tags have hypertext references (href’s) that point a link to another page. Set the href to whichever site or file you want your link to go to. 
  3. In between the opening and closing <a> tag, let’s create an <img> tag. Remember that image tags are self-closing. Add an attribute called src that will point to the url or path to the image you are using for your link. 
  4. Create something that will describe the image so the user knows it’s clickable. This could be a <caption> tags, a <div> tags, an <h2> element, a <p> tag – whatever you want it to be.

A working sample is in the code editor below. Definitely take some time to play around with it! 

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Image Link</title>
   <style>
       div {
           width: 500px;
           display: flex;
           flex-flow: column wrap;
       }
       img {
           width: 100%;
       }
       caption {
           width: 100%;
           height: 50px;
       }
   </style>
</head>
<body>
   <div>
       <a href="https://www.goldengate.org/" target="_blank" referrerpolicy="no-referrer">
           <img src="https://images.unsplash.com/photo-1449034446853-66c86144b0ad?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2100&q=80" alt="Golden Gate Bridge"  refer/>
       </a>
       <caption>
           An icon in the San Francisco skyline, the Golden Gate bridge shines in the twilight night sky. Click the image to learn more information about the Golden Gate bridge.
       </caption>
 
   </div>
</body>
</html>

One final note: It is tempting to put an <a> only around the caption – since that’s what the link is referring to. Users have come to expect that if they click on a picture, a new tab will open with the link destination (this is what the target=”_blank” syntax is doing). So, keep the <a> tag surrounding the link and leave the text to describe the picture – or put the <a> tag around both the text and <img>. Both ways are viable options.