diff --git a/tutorials/html/04-links-and-navigation/absolute-urls.mdx b/tutorials/html/04-links-and-navigation/absolute-urls.mdx index dbcbd4ed3..1940561ed 100644 --- a/tutorials/html/04-links-and-navigation/absolute-urls.mdx +++ b/tutorials/html/04-links-and-navigation/absolute-urls.mdx @@ -1,15 +1,355 @@ --- -id: absolute-urls -title: "Understanding Absolute URLs in HTML Links" +id: html-absolute-urls +title: "HTML Absolute URLs" sidebar_label: "Absolute URLs" sidebar_position: 3 slug: /html/links-and-navigation/absolute-urls -description: "Explore absolute URLs, including protocol definitions, domain names, port numbers, and when to use full external web paths in anchor tags." +description: "Learn what absolute URLs are in HTML and when to use them. Understand the parts of a full web address, schemes like https, mailto and tel, URL encoding, international domain names, query strings, common mistakes, and best practices on CodeHarborHub." keywords: - - absolute URLs HTML - - full path URLs - - HTTP HTTPS protocols - - domain name linking + - HTML absolute URL + - absolute URL vs relative URL + - HTML full web address + - URL parts scheme host path + - https vs http links + - URL encoding percent + - internationalized domain names + - query string in links + - HTML link best practices + - learn HTML URLs - CodeHarborHub HTML -tags: [html, urls, networking, beginner] ---- \ No newline at end of file +tags: [html, web-development, beginner, links, urls, absolute-urls, frontend] +--- + +Imagine you want to tell a friend how to reach your house. You could say, "Turn left at the corner," but that only works if they already know where they are standing. A far better way is to give the **full address**: house number, street, city, country. It works for anyone, starting from anywhere in the world. + +An **absolute URL** is exactly that: the full address of a page, image, or file on the web. It carries everything a browser needs to find the resource, with no guessing and no dependence on the page you are currently on. + + +
+ +## What You Will Learn + +- What makes a URL **absolute** +- Every part of a full web address, and what each one does +- Which **schemes** you can use, such as `https`, `mailto`, and `tel` +- How special characters, spaces, and international names are written in URLs +- When absolute URLs are the right choice, and when they are not +- Common mistakes, and how to avoid them + +## The Basics + +An absolute URL always starts with a **scheme** (also called a protocol), followed by `://` and the location. + + + + +```html title="index.html" +

+ Read the HTML guide on + MDN Web Docs. +

+

+ See the official standard at + the WHATWG website. +

+``` + +
+ + + +<> +

+ Read the HTML guide on{' '} + MDN Web Docs. +

+

+ See the official standard at{' '} + the WHATWG website. +

+ +
+ +
+
+ +The demo links point to `#` so they stay on this page. In your own file, they would go to the full addresses shown in the code. + +Because the address is complete, these links work **identically** on any page, in any folder, on any website. + +## Anatomy of an Absolute URL + +Let us take one long address apart. + +```text +https://user@www.example.com:8080/courses/html/index.html?lang=en&level=1#links +└─┬─┘ └─┬─┘└──────┬──────┘└─┬─┘└──────────┬───────────┘└────────┬─────┘└──┬─┘ +scheme user host port path query fragment +``` + +| Part | Example | What it does | +| :-- | :-- | :-- | +| **Scheme** | `https` | The rule for how to talk to the resource | +| **Authority** | `www.example.com:8080` | The host (server name) and an optional port | +| **Path** | `/courses/html/index.html` | Which page or file on that server | +| **Query** | `?lang=en&level=1` | Extra information, as name and value pairs | +| **Fragment** | `#links` | A spot within the page, handled by the browser | + +Most links you write use only three of these: scheme, host, and path. + +:::info You rarely type everything +The username (`user@`) and port (`:8080`) are uncommon on public websites. Browsers also hide default ports, which are 443 for `https` and 80 for `http`. You can safely ignore them in everyday links. +::: + +## Common Schemes + +The scheme tells the browser what kind of resource this is and how to open it. + +| Scheme | Example | What happens | +| :-- | :-- | :-- | +| `https` | `https://example.com` | A secure web page. This is the standard today | +| `http` | `http://example.com` | An unencrypted web page. Avoid for new links | +| `mailto` | `mailto:hello@example.com` | Opens the email app | +| `tel` | `tel:+911234567890` | Starts a phone call | +| `sms` | `sms:+911234567890` | Opens a text message | +| `ftp` | `ftp://files.example.com` | File transfer. Rare, and many browsers no longer support it | + +:::tip Use https +`https` encrypts the connection, so nobody can read or change the page on its way to the visitor. Almost every site supports it, and browsers warn visitors about plain `http`. Link to the `https` version whenever it exists. +::: + +You will meet `mailto:` and `tel:` links in detail in their own lessons later in this section. + +## Absolute URLs for Different Resources + +An absolute URL can point to anything on the web, not only pages. + + + + +```html +HTML 5.2 specification +``` + + + + +```html +Sunrise over a harbor, hosted on another site +``` + + + + +```html +Download the syllabus (PDF) +``` + + + + +```html + + Attributes of the anchor element + +``` + + + + +:::warning Hot-linking other people's files +Pointing an `` or file link at someone else's server uses their bandwidth, and the file can change or disappear without warning. Only do it with permission, or when the host clearly offers files for that purpose. +::: + +## Spaces, Symbols, and Other Languages + +URLs may contain only a limited set of characters. Anything else is written with a **percent sign** and a code. This is called **URL encoding**. + +| Character | In a URL | Note | +| :-- | :-- | :-- | +| Space | `%20` | Never type a raw space in a URL | +| `&` in a value | `%26` | In HTML, also write `&` between query parameters | +| `#` in a value | `%23` | Otherwise it starts the fragment | +| `é` in a value | `%C3%A9` | Non-English letters are encoded | +| `/` in a value | `%2F` | Otherwise it separates path parts | + + + + +```html +Résumé +``` + + + + +```html +Résumé +``` + + + + +Modern browsers often fix simple cases for you, but encoding makes your links reliable everywhere. When you create your own files, an even better habit is to **avoid spaces and special letters in file names**. Use lowercase letters, numbers, and hyphens, like `my-resume.pdf`. + +### Query Strings + +A query string passes extra information to the page. Names and values are paired with `=`, and pairs are separated by `&`. + +```html title="query.html" + + Beginner HTML results + +``` + +Notice `&` instead of `&`. In HTML, the ampersand starts a character reference, so writing `&` inside an attribute is the correct and safest form. The browser turns it back into `&` before it follows the link. + +## Web Addresses in Every Language + +The web is for everyone, and domain names do not have to be in English letters. An **internationalized domain name** (IDN) can contain letters from many scripts. + +```html title="idn.html" +München +例え +उदाहरण +``` + +Behind the scenes, the browser converts these into a plain ASCII form that starts with `xn--`. You can write the readable form in your HTML, and visitors will see the readable form too. + +A few points for a global audience: + +- **Link text is separate from the address.** The visible words can be in any language, while the `href` stays a valid URL. +- **Set `lang`** on link text in another language, as you learned in the [Anchor Element](./anchor-element) lesson. +- **Test with real addresses.** If a site uses unusual characters, click the link yourself before publishing. +- **Be careful with look-alike letters.** Some scripts have letters that look like Latin ones. Always check the address of a link you are given before sharing it. + +## When Should You Use Absolute URLs? + +Absolute URLs are right in these situations. + +| Situation | Why absolute works best | +| :-- | :-- | +| Linking to **another website** | There is no other way to name an outside address | +| Content that **leaves your site**, such as emails, newsletters, and social posts | The reader is not on your site, so relative paths would break | +| **Sitemaps, canonical links, and social preview tags** | Search engines and apps need the full address | +| Linking to a **shared resource on a CDN** | The file lives on a different host | +| **API requests** from your code to another service | The code must know exactly where to call | + +For links **inside your own site**, relative URLs are usually the better choice. That is the topic of the next lesson, [Relative URLs](./relative-urls). + +### Absolute vs Relative at a Glance + +| | Absolute URL | Relative URL | +| :-- | :-- | :-- | +| Example | `https://example.com/about.html` | `about.html` | +| Includes the scheme and host? | Yes | No | +| Works from any page? | Yes | Only from the right location | +| Easy to move your site? | No, you must edit each link | Yes, links keep working | +| Best for | Other websites | Your own pages | + +:::warning Do not hard-code your own domain everywhere +If you write `https://mysite.com/about.html` in every internal link, then moving the site to a new domain, or testing it on your computer, breaks every link. Use relative URLs inside your own site. +::: + +## Common Mistakes + +### Mistake 1: Forgetting the scheme + +```html + +Visit Example + + +Visit Example +``` + +Without `https://`, the browser treats `www.example.com` as a relative path, and the visitor lands on a "not found" page. + +### Mistake 2: Using `http` when `https` exists + +Plain `http` links can trigger warnings, and a secure page that loads `http` images may have them blocked ("mixed content"). Use `https`. + +### Mistake 3: Raw spaces and special characters + +Encode them, or better, avoid them in file names. + +### Mistake 4: Typing `&` instead of `&` in query strings + +Browsers usually forgive it, but `&` is the correct form and avoids surprises, especially when a parameter name looks like a character reference. + +### Mistake 5: Copying very long, messy URLs + +Many shared addresses carry tracking parameters that you do not need, such as `?utm_source=...`. Remove what the page does not require, so your link stays short, clean, and private. + +### Mistake 6: Ignoring broken links + +Outside pages move and disappear. Check your external links from time to time, and prefer stable, official addresses. + +## Try It Yourself + +Here is a short project. + +1. Create a file called `useful-sites.html`. +2. Add an `

` that says **Useful Sites for Learners**. +3. Make a list of **four** absolute links to websites you trust. Use `https` for each. +4. Add one link with a **query string**, and write the `&` as `&`. +5. Add one link to a file with a space in its name, and write the encoded version with `%20`. +6. Try removing `https://` from one link, open the page, and click it. What happens? Fix it again. +7. Bonus: add a link whose text is in another language, with the correct `lang` attribute. + + +
+ +## Quick Recap + +Click a question to check your answer. + +
+1. What makes a URL absolute? + +It contains the full address, starting with a scheme such as `https://` and including the host, so it works from any page. + +
+ +
+2. What happens if you write `href="www.example.com"` with no scheme? + +The browser treats it as a relative path on your own site, so the link usually leads to a "not found" page. + +
+ +
+3. Which scheme should you choose for web pages, and why? + +`https`, because it encrypts the connection and avoids browser security warnings. + +
+ +
+4. How do you write a space inside a URL? + +As `%20`. Even better, avoid spaces in file names and use hyphens. + +
+ +
+5. When should you prefer a relative URL over an absolute one? + +For links between pages inside your own site, so the links keep working if you move the site to another domain or test it locally. + +
+ +## Key Takeaways + +- An **absolute URL** is a complete address: scheme, host, and path. +- Always include the scheme, and prefer `https`. +- Use absolute URLs for other websites, emails, social posts, sitemaps, and shared resources. +- Encode spaces and special characters, and write `&` as `&` in query strings. +- Use relative URLs for links inside your own site, and check external links regularly. + +You now know how to point to any place on the web. Next, learn how to link your own pages with shorter paths in [Relative URLs](./relative-urls). \ No newline at end of file diff --git a/tutorials/html/04-links-and-navigation/anchor-element.mdx b/tutorials/html/04-links-and-navigation/anchor-element.mdx index 47b58cb4c..e4d4d7c23 100644 --- a/tutorials/html/04-links-and-navigation/anchor-element.mdx +++ b/tutorials/html/04-links-and-navigation/anchor-element.mdx @@ -1,15 +1,400 @@ --- -id: anchor-element -title: "The HTML Anchor Element: Creating Hyperlinks" -sidebar_label: "Anchor Element ()" +id: html-anchor-element +title: "HTML Anchor Element" +sidebar_label: "Anchor Element" sidebar_position: 2 slug: /html/links-and-navigation/anchor-element -description: "Learn how the HTML anchor element (a tag) works, its essential href attribute, and how it connects web pages together across the internet." +description: "Learn how the HTML anchor element works. Understand the a tag, the href attribute, link text, link states, styling links with CSS, linking images, accessibility, hreflang for multilingual sites, and common mistakes on CodeHarborHub." keywords: - HTML anchor element - - a tag HTML - - href attribute syntax - - hyperlink creation + - HTML a tag + - HTML href attribute + - HTML hyperlink + - HTML link text + - HTML link states + - style links with CSS + - link an image in HTML + - hreflang attribute + - HTML link accessibility + - learn HTML links - CodeHarborHub HTML -tags: [html, anchor-tag, links, beginner] ---- \ No newline at end of file +tags: [html, web-development, beginner, links, anchor, frontend] +--- + +Every link you have ever clicked, from a search result to a "Buy now" button to a footnote, started with the same tiny tag. It is called the **anchor element**, and it is written ``. + +The name comes from the idea of a ship's anchor: something that holds a spot and connects it to somewhere else. Learn this one element well and everything else in this section, from internal links to navigation menus, becomes much easier. + + +
+ +## What You Will Learn + +- How the `
` element and its `href` attribute work together +- What can go inside a link, including text, images, and more +- The five link states, and how to style each one +- How to write link text that works for every visitor +- How to make icon-only links accessible +- How to use `hreflang`, `title`, and `lang` on links +- Common mistakes, and how to avoid them + +## The Basics + +An anchor needs two things: an `href` attribute that says **where** to go, and content that says **what** to click. + + + + +```html title="index.html" +

+ Explore the + MDN Web Docs + to learn more. +

+``` + + + + + +<> +

+ Explore the{' '} + MDN Web Docs{' '} + to learn more. +

+ +
+ +
+ + +The demo link points to `#` so it stays on this page. In your own file, it would go to the address in `href`. + +## The `href` Attribute + +`href` stands for **hypertext reference**. Its value can be many different things. + +| `href` value | Where it goes | +| :-- | :-- | +| `https://example.com` | Another website | +| `about.html` | Another file in the same folder | +| `#contact` | A spot on the current page | +| `mailto:hi@example.com` | A new email message | +| `tel:+911234567890` | A phone call | +| `files/guide.pdf` | A file, which opens or downloads | + +An `` **without** `href` is called a placeholder link. It looks like plain text, cannot be clicked, and cannot be reached with the keyboard. + +```html +I am not a link yet +``` + +:::tip When is a placeholder useful? +It is handy in templates and menus where the current page's item should not link to itself. Otherwise, always give an anchor an `href`. +::: + +## What Can Go Inside a Link? + +Links are **inline** elements, so they live inside text. But they can wrap many things. + + + + +```html +Browse all courses +``` + + + + +```html + + CodeHarborHub home + +``` + +When an image is the only content of a link, its `alt` text becomes the link text. Describe where the link **goes**, not what the picture looks like. + + + + +```html + +

HTML for Beginners

+

Build your first web page in a weekend.

+
+``` + +Modern HTML lets one link wrap a whole card, including headings and paragraphs. Keep the card short, so a screen reader announces something sensible. + +
+
+ +:::warning Never put a link inside another link +An `` cannot contain another ``, and it should not contain buttons or form controls. Browsers cannot decide which one to follow. +::: + +## Link States + +A link is not one thing. It changes as people use it. CSS lets you style each situation with a **pseudo-class**. + +| State | Pseudo-class | When it applies | +| :-- | :-- | :-- | +| Unvisited | `:link` | The visitor has not been to this address | +| Visited | `:visited` | The visitor has already been there | +| Hover | `:hover` | A mouse pointer is over the link | +| Focus | `:focus-visible` | The link is reached with the keyboard | +| Active | `:active` | The link is being pressed | + +Remember the order with the phrase **L**o**V**e **F**ear **H**ate **A**ctive, or "LVFHA": link, visited, focus, hover, active. If you write them in a different order, later rules can cancel earlier ones. + + + + +```html title="link-states.html" + + +

Visit the example site.

+``` + + + + + +<> +

+ Visit the{' '} + example site. +

+ +
+ +
+ + +:::info Why browsers limit `:visited` +For privacy, browsers only let `:visited` change a few properties, such as color. Otherwise a website could detect which sites you have visited. +::: + +## Writing Good Link Text + +Link text is the most important thing you control. Follow these simple habits. + +1. **Say where it goes.** "Download the course syllabus" beats "click here." +2. **Keep it short but clear.** Aim for two to six words. +3. **Put the key words first.** People scan the start of a link. +4. **Avoid repeating the same text for different places.** Two links that both say "Read more" cannot be told apart. +5. **Do not include the word "link."** Screen readers already announce it. + + + + +```html +

Our new course is out. Click here.

+

The CSS guide is ready. Click here.

+``` + +
+ + +```html +

Our new CSS course is out.

+

The CSS guide is ready.

+``` + +
+
+ +## Icon-Only Links + +Sometimes a link is only an icon, like a social media logo or a search symbol. A screen reader needs words to announce. There are two clean ways to give them. + +```html title="icon-links.html" + + + CodeHarborHub on the example network + + + + + + +``` + +The `aria-hidden="true"` on the SVG stops the picture from being read out, and the `aria-label` gives the link its name. + +## The `title` Attribute + +You can add a `title` to give extra information as a tooltip. + +```html +Course guide +``` + +Use it with care. Tooltips need a mouse, so touch and keyboard users often never see them. Never put **essential** information only in `title`. Put it in the visible text instead. + +## Multilingual Links: `hreflang` and `lang` + +If your site has pages in several languages, two attributes help. + +| Attribute | What it does | Example | +| :-- | :-- | :-- | +| `hreflang` | Says what language the **destination** page is in | `hreflang="hi"` | +| `lang` | Says what language the **link text** is in | `lang="hi"` | + + + + +```html title="languages.html" + +``` + + + + + +<> + + + + + + + +A good habit for a language switcher is to write each language **in its own language**, as above. A visitor who cannot read English can still find their option. + +:::note +Inside ``, the output uses `hrefLang` because that block is JSX. In plain HTML, write `hreflang`. +::: + +## Accessibility Checklist + +- **Use a real ``** for navigation. Do not build links from a `
` or `` with JavaScript. Those cannot be reached with the keyboard by default and do not announce as links. +- **Keep the focus outline visible.** Never write `outline: none` without a replacement. +- **Do not rely on color alone.** Keep the underline, or add another clear cue, so people who cannot tell colors apart can still find links. +- **Make the target big enough.** On phones, aim for a touch area of about 44 by 44 pixels. Add `padding` to small links. +- **Use a link for going somewhere, and a button for doing something.** Links navigate. Buttons act, like submitting a form or opening a menu. + +| The click will... | Use | +| :-- | :-- | +| Go to a page, file, or spot on a page | `` | +| Run an action on the current page | ` +``` + +### Mistake 6: Writing the address in the text and not the link + +If you show a URL, make the whole URL the link, or better, use readable words. + +## Try It Yourself + +Here is a short project. + +1. Create a file called `my-links.html`. +2. Add an `

` that says **My Favorite Sites**. +3. Make a list of three links to your favorite websites, each with clear link text. +4. Make one link wrap an image, and give the image a useful `alt` text. +5. Add a CSS rule for `a:link`, `a:visited`, `a:hover`, and `a:focus-visible`, in that order. +6. Press Tab to move through the links. Can you always see which link has focus? +7. Bonus: add a small language switcher using `hreflang` and `lang`. + + +
+ +## Quick Recap + +Click a question to check your answer. + +
+1. Which attribute makes an `` element a real link? + +The `href` attribute. Without it, the anchor is only a placeholder. + +
+ +
+2. What can an `` element contain? + +Text, images, and other inline or block content, but never another link or a button. + +
+ +
+3. Which pseudo-class styles a link reached with the keyboard? + +`:focus-visible`. + +
+ +
+4. Why is "click here" poor link text? + +It does not describe the destination. People scanning the page or using a screen reader cannot tell links apart. + +
+ +
+5. How do you give an icon-only link an accessible name? + +Add `alt` text to an image icon, or add `aria-label` to the link and hide a decorative SVG with `aria-hidden="true"`. + +
+ +## Key Takeaways + +- The `
` element with an `href` attribute is the foundation of every link. +- The `href` value decides where the link goes: a site, a page, a section, an email, a phone number, or a file. +- Style links with `:link`, `:visited`, `:focus-visible`, `:hover`, and `:active`, in that order. +- Write link text that describes the destination, and name icon-only links with `alt` or `aria-label`. +- Use `` to go somewhere and ` + + + +``` + +Notice that the control is a ` + + + +``` + +```css title="mobile-menu.css" +.menu-toggle { display: none; } /* hidden on wide screens */ + +.menu { + display: flex; + gap: 0.5rem; + margin: 0; + padding: 0; + list-style: none; +} + +@media (max-width: 40rem) { + .menu-toggle { + display: inline-block; + padding: 0.75rem 1rem; + } + .menu { display: none; flex-direction: column; } + .menu.is-open { display: flex; } +} +``` + +```js title="mobile-menu.js" +const toggle = document.querySelector(".menu-toggle"); +const menu = document.getElementById("main-menu"); + +toggle.addEventListener("click", () => { + const open = toggle.getAttribute("aria-expanded") === "true"; + toggle.setAttribute("aria-expanded", String(!open)); + menu.classList.toggle("is-open", !open); +}); + +// Let the Escape key close the menu and return focus to the button +document.addEventListener("keydown", (event) => { + if (event.key === "Escape" && toggle.getAttribute("aria-expanded") === "true") { + toggle.setAttribute("aria-expanded", "false"); + menu.classList.remove("is-open"); + toggle.focus(); + } +}); +``` + +This is a simple **disclosure pattern**. A button shows or hides a section. It is much easier to use correctly than a complicated menu widget. + +:::info Why `aria-expanded` and `aria-controls`? +`aria-expanded="true"` or `"false"` tells a screen reader if the menu is currently open. `aria-controls` points to the element the button controls. Together they make the button announce something like "Menu, collapsed, button." +::: + +If you build with a framework such as Docusaurus, the site's own navbar already does this for you. Understanding the pattern is still valuable, so you can build and fix menus yourself. + +## Dropdown Menus: Handle With Care + +Dropdowns are popular, but they cause many accessibility problems: + +- They often open only on **hover**, which touch screens and keyboards cannot do. +- They are hard to use with a **shaky hand**, since the menu closes when the pointer slips. +- Screen reader users may not know there are hidden links. + +If you need a dropdown, build it as a **disclosure** too: a button that opens a nested list of normal links. + +```html title="dropdown.html" + +``` + +JavaScript toggles the `hidden` attribute and updates `aria-expanded`, just as in the mobile menu. Opens on click or Enter, closes with Escape, and works on touch screens. + +:::warning Avoid `role="menu"` for site navigation +The ARIA `menu` role is meant for application menus, like the File menu in a word processor. It changes how keyboards and screen readers behave, and it is a common mistake on websites. For a site menu, use a plain `