Category: HTML

  • Button onclick versus href: Choose the Right Navigation Element

    Button onclick versus href: Choose the Right Navigation Element

    For a button onclick href comparison, choose the element by its action, not its appearance. Use an anchor with an href when activation takes the user to another URL, document, download, or in-page location. Style that anchor to look like a button. Use a real button when activation performs an in-page action or requires JavaScript to decide what happens.

    This distinction preserves browser behavior. Anchors support link interactions such as opening a destination in a new tab, copying a link address, and following a URL without JavaScript. Buttons communicate an action. A button can trigger navigation with JavaScript, but that does not make it a semantic substitute for an anchor.

    Button onclick versus href: use an anchor for navigation

    An anchor is the correct element when the result is navigation to a known destination. Its href should contain the URL, so browsers, assistive technologies, search engines, and users can identify the destination before activating it.

    Use an anchor for paths such as /about, full URLs, document downloads, email links, and fragment links such as #features. If an HTML button onclick link sends the user to a known URL, replace that pattern with an anchor and style the anchor instead.

    Do not add an href attribute to a button element. The two elements have different semantic roles, even when they share the same visual design.

    Style an anchor with href to look like a button

    Apply button-like CSS to the anchor while keeping its link behavior. The anchor remains discoverable as a destination and can still receive normal browser focus and link commands.

    HTML: <a class=”button-link” href=”/pricing”>View plans</a>

    CSS: .button-link { display: inline-block; padding: .75rem 1rem; border-radius: .35rem; background: #1769aa; color: #fff; text-decoration: none; font-weight: 600; } .button-link:focus-visible { outline: 3px solid #111; outline-offset: 2px; }

    Use sufficient color contrast and preserve a clear focus indicator. A class changes the presentation, not the meaning: this remains a link because it takes the user to another location.

    Use HTML button navigation with onclick for real actions

    Use a button when activation performs an action in the current interface, such as opening a dialog, toggling a menu, applying a filter, or deleting an item. HTML button onclick navigation is appropriate only when the action genuinely needs JavaScript, such as computing a destination after validation or saving state before redirecting.

    Example: <button type=”button” onclick=”location.assign(‘/account’)”>Open account</button>

    location.assign() navigates the current document to the supplied URL and normally adds that destination to the browser history, allowing the user to return with the Back button. The equivalent property form is location.href = ‘/account’; it also navigates the current page and normally creates a history entry. Neither method opens a new tab.

    Set type=”button” when the control sits inside a form and is not meant to submit it. Without that type, a button inside a form defaults to submission. If JavaScript is unavailable and the destination is known in advance, prefer an anchor so navigation still works.

    Choose by action, not appearance

    • Navigate to a URL, document, download, or page section: use an anchor with href.
    • Open, close, toggle, filter, select, or delete within the page: use a button.
    • Send form data through the form’s normal process: use <button type=”submit”> or the form’s submit control.
    • Navigate only after JavaScript performs a required action: use a button with JavaScript, such as location.assign().

    Choose semantics first, then make the selected element match the interface design. A button-shaped anchor is still navigation; a button with onclick is still an action control.

  • HTML hr tag: Mark a Thematic Break and Style It with CSS

    HTML hr tag: Mark a Thematic Break and Style It with CSS

    The HTML hr tag marks a thematic break between parts of a document. It tells browsers and assistive technologies that the subject, scene, section, or topic has changed; it is not simply a generic decorative line.

    Use an hr element in HTML when the separation has meaning. Use CSS borders on another element when you only need a visual edge around a card, panel, or layout region.

    What does the HTML hr tag represent?

    The hr element represents a transition within a page. Common uses include separating chapters, dividing sections of an article, or marking a change in topic. Its meaning comes from the document structure, not from its default appearance as a horizontal rule.

    Do not insert an hr after every paragraph or use it as a replacement for all decorative dividers. If removing the line would remove no meaningful separation, a border or background on an existing container is usually the better choice.

    How do you write an hr element in HTML?

    The element is void, so it has no closing tag. Write it as <hr> wherever the thematic break belongs in the content flow.

    HTML: <p>The first chapter ends here.</p> <hr> <p>The next chapter begins here.</p>

    Place the element between the related content blocks, rather than at the beginning or end of an unrelated container. Browsers supply default styling, but that appearance varies by browser and may not match the design.

    How do you control hr width in CSS, height, borders, color, and backgrounds?

    Set the width, remove the browser’s default border, and create a controlled top border for a crisp line:

    Border-based: hr { width: 60%; border: 0; border-top: 2px solid #6b7280; }

    A percentage width is calculated against the containing block’s content width, not the viewport. If the containing block is 800px wide, a 60% rule produces a line that is normally 480px wide. A fixed value such as width: 20rem provides a more consistent measure when the design requires one.

    For a background-based treatment, give the element a height and remove its border:

    Background-based: hr { width: 60%; height: 4px; border: 0; background-color: #2563eb; }

    Use a border when the line should behave like a narrow stroke. Use a background when you need a thicker bar or plan to add effects such as a gradient. The color property alone may not change a browser’s default rule consistently, so set border-color, border-top, or background-color explicitly.

    How do you control alignment and spacing around an hr?

    Center a narrower rule with automatic inline margins and control its surrounding whitespace with the margin shorthand:

    Centered and spaced: hr { width: 60%; margin: 2rem auto; border: 0; border-top: 2px solid #d1d5db; }

    Here, 2rem adds space above and below the thematic break, while auto divides the remaining horizontal space evenly. For separate control, use margin-block: 2rem and margin-inline: auto. Keep the spacing on the rule instead of adding empty paragraphs, so the document retains a clear content structure.

  • HTML Blank Space: How to Add Space in HTML

    HTML Blank Space: How to Add Space in HTML

    To add HTML blank space, first identify what should receive the space. Use CSS margin or padding for layout, a non-breaking space for one intentional gap inside text, and preformatted rules when source spacing or line breaks must survive. Whether the task is described as “blank space HTML” or “empty space HTML,” this choice prevents spacing hacks and keeps the result predictable.

    CSS is the default for separating elements. HTML whitespace controls text rendering; it is not a reliable tool for building page geometry.

    How do you add HTML blank space with margin and padding?

    Use margin to create space outside an element and padding to create space between its content and its border. These are the normal CSS tools for spacing paragraphs, headings, cards, buttons, and sections.

    For example, set p { margin-bottom: 1rem; } to separate paragraphs. Give a panel internal breathing room with .panel { padding: 1rem; }. Margin moves neighboring elements apart, while padding enlarges the element’s interior area and carries its background and border with it.

    For an empty visual region, use a defined layout property such as min-height: 8rem; or suitable padding. Do not create a blank region by inserting multiple spaces into the HTML source.

    Why do repeated spaces collapse in HTML?

    In normal HTML text, browsers collapse consecutive spaces, tabs, and line breaks into a single rendered space. Leading and trailing whitespace may also disappear at an element’s edges. For example, several spaces between two words usually display as one space, regardless of how many appear in the source.

    This behavior keeps source formatting from changing the page layout accidentally. It also explains why pressing the spacebar repeatedly does not create dependable spacing between elements. Apply margin, padding, or another layout rule when the distance must remain consistent across screen sizes.

    When should you use &nbsp; for a blank space in HTML?

    Use the non-breaking space entity, written as &nbsp;, for a specific text-level purpose: keeping adjacent content together so the browser cannot break the line between it. A common example is a number and its unit, such as 10&nbsp;kg, or a title and a short suffix that should remain together.

    A non-breaking space also creates one visible space where ordinary whitespace would collapse. It is appropriate for an intentional typographic gap inside a sentence, but it is not a substitute for CSS layout. Avoid chains of non-breaking spaces to position text, align columns, or create large empty areas. Those spaces become fragile when fonts, content, or viewport sizes change.

    How do pre and white-space values preserve empty space in HTML?

    Use the <pre> element when the content itself depends on its original spaces and line breaks, such as a code sample, text file, or fixed-format output. Content inside this element normally preserves source whitespace and uses a monospace presentation. It can also wrap the content in CSS when long lines need to fit.

    The white-space CSS property gives more precise control when the content should remain in an ordinary element:

    • normal: Collapses spaces and line breaks and wraps text. This is the default behavior.
    • nowrap: Collapses whitespace but prevents the text from wrapping onto another line.
    • pre: Preserves spaces and line breaks but does not wrap lines automatically.
    • pre-wrap: Preserves spaces and line breaks while allowing long lines to wrap.
    • pre-line: Preserves line breaks but collapses repeated spaces.

    Choose pre-wrap for user-entered text where formatting matters but overflow should be avoided. Choose pre-line when submitted line breaks matter but repeated indentation does not.

  • How to Open an HTML Link in a New Tab

    How to Open an HTML Link in a New Tab

    To open an HTML link in a new tab, add the target=”_blank” attribute to a normal anchor. Keep the destination in href, then place the visible link text between the opening and closing a tags. This pattern requests a new browsing context without JavaScript and works for ordinary text navigation.

    The browser or the user’s settings ultimately determine whether that new context appears as a tab or a window. Therefore, target=”_blank” requests the behavior; it does not guarantee a particular piece of browser interface.

    How to Open an HTML Link in a New Tab: The Complete Anchor Example

    Use this complete anchor when the link should request a separate browsing context:

    <a href=”https://example.com/resources” target=”_blank” rel=”noopener”>Open the resource</a>

    The href attribute contains the destination URL. The target attribute controls where the browser requests that destination, and _blank names a new, unnamed browsing context. The words “Open the resource” become the clickable link text.

    rel=”noopener” is a useful companion for links that open another document. It prevents the newly opened page from using the opener reference to interact with the original page. It does not create the new tab; target=”_blank” makes that request.

    How Does target=”_blank” Change Navigation?

    Without a target attribute, a link normally loads its href in the current browsing context. With target=”_blank”, the browser asks for a new top-level context instead. In common desktop configurations, that context appears as a new tab, while some configurations open a new window.

    • The original page remains available in its existing tab or window.
    • The destination loads in the newly requested context.
    • The browser may apply popup-blocking, tab preferences, or other user controls.

    The keyword _blank does not force a physical tab. A browser or user setting ultimately decides whether the result is a tab or a window. Keyboard commands and accessibility preferences can also affect how a link opens. The HTML declares the requested browsing context, not the final interface choice.

    How Do You Use an HTML href to Open a Link in a New Tab?

    An href for a new tab is still an ordinary URL paired with target=”_blank”. Apply the same pattern to text links, product names, documentation references, or any other element that users expect to activate as a link:

    <a href=”/documentation” target=”_blank” rel=”noopener”>Read the documentation</a>

    For an image link, place the image element inside the anchor and keep the same attributes on the anchor:

    <a href=”/gallery” target=”_blank” rel=”noopener”><img src=”/images/gallery-preview.jpg” alt=”View the image gallery”></a>

    The image becomes clickable because it is nested inside the a element. Provide meaningful alt text so users who cannot see the image still understand the link’s purpose. The anchor’s href remains the destination, while its target requests the separate context.

    When Is Same-Tab Navigation Clearer?

    Same-tab navigation is often clearer when the destination is part of the same task or site journey. It preserves the browser’s normal back-button flow and avoids accumulating extra tabs. Omit the target attribute for the default behavior, or state it explicitly:

    <a href=”/account” target=”_self”>Open your account</a>

    • Use same-tab navigation for related pages, form steps, account areas, and primary site content.
    • Request a new context for supporting resources that users may need to consult while keeping the current page open.
    • Describe the destination clearly so users can choose how they want to open it.

    Use target=”_blank” deliberately rather than on every link. The clearer choice depends on whether preserving the current page helps the user complete the task.

  • HTML dialog: Modal and Non-Modal Examples

    HTML dialog: Modal and Non-Modal Examples

    Use the native HTML dialog element to build a modal or non-modal interface without recreating its focus and keyboard behavior with a generic div. The example below is a complete HTML dialog with two triggers, a method=dialog form, and JavaScript for opening and closing it.

    When a dialog is shown, the element receives the open state. The opening method determines whether the rest of the page remains interactive.

    Create an HTML dialog box with a form close action

    Place the trigger buttons and dialog in the document. A form with method=”dialog” closes its nearest dialog when a submit button is activated. The clicked button’s value becomes the dialog’s return value.

    Markup: <button type=”button” id=”open-modal”>Open modal</button> <button type=”button” id=”open-nonmodal”>Open non-modal</button> <dialog id=”account-dialog”> <form method=”dialog”> <h2>Account settings</h2> <p>Choose an action for this account.</p> <button value=”cancel”>Cancel</button> <button value=”save”>Save</button> </form> </dialog>

    The two buttons use type=”button” so they do not submit a surrounding form. The dialog’s Cancel and Save buttons are submit controls for the dialog form, so either one closes the dialog without requiring a custom click handler.

    Open an HTML5 dialog with show() or showModal()

    Call show() for non-modal behavior. The dialog opens, but users can still interact with the rest of the page. Call showModal() for modal behavior. The browser renders a backdrop, keeps interaction inside the dialog, and manages modal focus.

    JavaScript: const dialog = document.querySelector(“#account-dialog”); const modalButton = document.querySelector(“#open-modal”); const nonModalButton = document.querySelector(“#open-nonmodal”); modalButton.addEventListener(“click”, () => { dialog.showModal(); }); nonModalButton.addEventListener(“click”, () => { dialog.show(); });

    • show() opens the dialog without making the document modal.
    • showModal() opens it as a modal dialog and enables ::backdrop styling.
    • Both methods set dialog.open to true. Do not call either method again while the same dialog is already open.

    Close the dialog, handle events, and read a return value

    Pressing Escape on a modal dialog normally fires the cancel event and then closes the dialog. Listen for cancel when you need to prevent that default behavior, such as when unsaved changes require confirmation. The close event fires after any closing method, including a dialog-form submission.

    Use close(value) to close the element from JavaScript. Its optional value is exposed through dialog.returnValue. The form buttons above return cancel or save.

    Closing and events: dialog.addEventListener(“cancel”, (event) => { /* event.preventDefault() keeps it open */ }); dialog.addEventListener(“close”, () => { console.log(dialog.returnValue); }); dialog.close(“programmatic”);

    After close(), the open property becomes false. The close event is the suitable place to update the page based on the selected value, while the cancel event is the suitable place to intercept Escape before the default close occurs.

    Style the HTML dialog and its ::backdrop

    Target the dialog directly for its panel appearance. The ::backdrop pseudo-element applies to the viewport layer created by showModal(); a non-modal dialog does not receive that modal backdrop.

    CSS: dialog { border: 0; border-radius: 0.5rem; padding: 1.5rem; max-width: 32rem; } dialog::backdrop { background: rgb(0 0 0 / 55%); }

    Keep the close controls inside the dialog form when their purpose is to return a user-selected result. Use close(value) for programmatic outcomes that are not represented by a form button.

  • HTML fieldset: Group Related Form Controls with legend and CSS

    HTML fieldset: Group Related Form Controls with legend and CSS

    An HTML fieldset groups form controls that belong to one topic, while a legend names that group. This gives screen-reader users a clear question or category before they encounter the controls. Build the semantic structure first, then use CSS to add the visual boundary, spacing, and layout.

    The HTML fieldset tag is especially useful for radio buttons because the shared name makes the inputs one-choice controls, while the legend identifies what that choice answers.

    How does an HTML fieldset group related controls?

    Place related controls inside fieldset and put the group label in its first child, legend. Unlike a heading styled to look similar, legend is programmatically associated with the fieldset. Each control still needs its own label. Connect a label’s for value to the input’s unique id, so clicking the text also selects or focuses the control.

    Use one name for mutually exclusive radio buttons, and give every option a distinct value. Do not use placeholder text as a substitute for a label: placeholders disappear and do not identify a completed choice reliably.

    How does the HTML fieldset tag work in a radio-button form?

    This complete radio-button form includes the group label, three individually labelled options, and a submit control:

    Complete markup: <form action=”/preferences” method=”post”> <fieldset> <legend>Contact preference</legend> <input type=”radio” id=”email” name=”contact” value=”email” required> <label for=”email”>Email</label> <input type=”radio” id=”phone” name=”contact” value=”phone”> <label for=”phone”>Phone</label> <input type=”radio” id=”none” name=”contact” value=”none”> <label for=”none”>No contact</label> </fieldset> <button type=”submit”>Save preference</button> </form>

    The legend, “Contact preference,” labels the entire group. Each label identifies one answer, and the matching for and id attributes preserve that relationship even if the visual layout changes. The shared contact name lets the browser enforce a single radio selection. The required attribute on one radio makes choosing an option mandatory for the group.

    How do you disable an entire fieldset?

    Add the disabled attribute to the fieldset opening tag when the whole group is unavailable:

    Disabled group: <fieldset disabled> <legend>Contact preference (unavailable)</legend> … </fieldset>

    Disabled fieldset controls cannot receive focus or user input, and their values are not submitted with the form. The legend remains readable, which allows the group’s status to be communicated. Keep important explanatory text in the legend or nearby content rather than placing interactive controls inside the legend.

    How do you style a CSS fieldset?

    Use a CSS fieldset rule for the border, padding, and internal layout. Style legend separately because browsers apply their own default border placement and spacing:

    CSS: fieldset { border: 2px solid #b8c0cc; padding: 1rem; display: grid; gap: .5rem; max-inline-size: 24rem; } legend { padding-inline: .5rem; font-weight: 700; } fieldset label { display: flex; align-items: center; gap: .5rem; }

    The border creates the visual group, while padding keeps controls away from its edge. The grid display and gap property provide consistent vertical spacing without adding presentational markup. The label rule aligns each radio button with its text and enlarges the useful click area. Adjust the border color, thickness, and maximum width to match the surrounding form while keeping sufficient contrast.

  • HTML main: How to Mark Up Primary Page Content

    HTML main: How to Mark Up Primary Page Content

    The HTML main element identifies the dominant content unique to the current document. Put the page’s article, product details, search results, dashboard view, or other primary task inside <main>; keep repeated site chrome outside it. The element also exposes a main landmark to assistive technology.

    Use one non-hidden main landmark at a time. A page can contain several main elements in its source when inactive views are hidden, but users should normally encounter only one exposed main landmark.

    What belongs in the HTML main element?

    Content belongs in the HTML main element when it distinguishes this document or view from other pages on the site. It should answer the page’s primary purpose rather than describe the surrounding website.

    • An article page’s heading, publication details, body, and related in-article sections.
    • A product page’s product information, pricing, specifications, and purchase controls.
    • A search page’s search heading, filters that control the results, and result list.
    • A dashboard’s active report, task area, or application view.

    The main element may contain headings, paragraphs, lists, forms, articles, sections, and other elements needed to present that content. A page-specific sidebar can belong inside <main> when it directly supports the document, while a repeated site-wide sidebar generally belongs outside it.

    A complete page structure: where main content fits

    Place <main> inside <body>, alongside the page’s repeated structural landmarks. A compact structure looks like this:

    <body> <header>Site identity</header> <nav>Primary links</nav> <main>Unique page content</main> <aside>Related site content</aside> <footer>Site information</footer> </body>

    • Header: identifies the site or page and may contain branding or introductory material.
    • Navigation: provides links for moving through the site or application.
    • Main: contains the document’s dominant, page-specific content.
    • Aside: contains tangential or supporting content, such as related links.
    • Footer: contains closing information, legal links, or repeated contact details.

    For an article, the article heading and text usually sit inside <main>. An article-specific header can sit inside the article, while the site header remains a sibling of main.

    How HTML main differs from header, nav, aside, and footer

    These elements describe different structural responsibilities. Location alone does not determine whether content belongs in main.

    • <header> introduces a site, page, article, or section. A site-wide header is repeated boilerplate, not the page’s main content.
    • <nav> groups navigation links. Primary menus, account menus, and breadcrumb navigation should not be placed in main merely because they appear above the content.
    • <aside> holds content related to, but separate from, the primary flow. A recurring “Most popular” panel or advertising block usually belongs outside main.
    • <footer> provides closing information for the site, page, article, or section. A repeated site footer does not become main content.

    Use <section> inside main for a thematic group that needs its own heading. Use <article> for a self-contained item, such as a post or product review. The main element is the broader landmark that contains the page’s primary experience.

    Can hidden views expose more than one HTML main element at once?

    Normally, expose only one non-hidden HTML main element at a time. Assistive technology uses the main landmark as a shortcut to the primary content, so multiple simultaneously exposed main landmarks can create ambiguity.

    Application shells and single-page interfaces may keep several views in the document. In that case, keep the active view in one main element and hide inactive views with the HTML hidden state or an equivalent accessibility-safe mechanism. For example, an inactive view can be represented as <main hidden>, while the active view remains exposed.

    • Do not leave several alternate screens visible and mark each one as main.
    • Do not rely only on visual positioning to hide an inactive landmark from assistive technology.
    • When switching views, remove the hidden state from the new main view before exposing it and hide the previous one.

    If the application uses one persistent main landmark and swaps its contents, that also satisfies the one-visible-main pattern.

  • Footer HTML: Complete Examples for Pages and Articles

    Footer HTML: Complete Examples for Pages and Articles

    Footer HTML marks supporting information for the nearest page or section. Use one document-level footer for site-wide details, or place a footer inside an article when the information belongs specifically to that article.

    The element provides meaning, not a fixed visual position. CSS determines whether the footer stays in normal flow, appears at the bottom of a layout, or changes position at a particular viewport width.

    What does footer HTML represent, and does it set a visual position?

    The footer element represents closing or supporting content for its nearest sectioning context. At page scope, it describes information about the whole document. Inside an article, it describes information about that article. Inside another sectioning element, such as section, it belongs to that section.

    A footer tag HTML example is interpreted by this surrounding structure; the element does not automatically mean “the bottom of the screen.” It can contain copyright information, related links, author details, publication dates, contact information, or other content associated with its scope.

    A document footer does not have to be the final child of the body. Place it where the document structure and reading order make sense, then use CSS for spacing, alignment, columns, backgrounds, or fixed positioning.

    How should a document-level footer be marked up with site information and navigation?

    Use a document-level footer for information that supports the entire site or page. Site identification, a navigation list, legal links, and general contact details are appropriate examples. The following footer HTML code shows those items together:

    <footer> <p>&copy; 2025 Example Journal</p> <nav aria-label=”Footer navigation”> <ul> <li><a href=”/about”>About</a></li> <li><a href=”/privacy”>Privacy</a></li> <li><a href=”/contact”>Contact</a></li> </ul> </nav> <address>Email: <a href=”mailto:[email protected]”>[email protected]</a></address> </footer>

    The nav element identifies the group as navigation, while the list organizes its links. The address element is suitable for contact information related to the site or its owner. A footer can contain several navigation groups, but each group should have a clear purpose and accessible label.

    For a page-specific shell, the same structure can sit after the main content inside a wrapper. Its scope remains document-level if it is not nested inside an article or another sectioning context.

    When should you use the HTML footer tag inside an article for author metadata?

    Use an article footer when the information describes the article rather than the whole site. Common content includes the author, publication date, update date, categories, tags, licensing information, or links to related article resources.

    This example shows an article footer with author metadata:

    <article> <h2>Choosing Accessible Color Contrast</h2> <p>Readable contrast supports visitors across devices and lighting conditions.</p> <footer> <p>Written by Maya Chen</p> <p>Published on January 12, 2025; updated on February 3, 2025</p> </footer> </article>

    Here, the inner footer belongs to the article because it is nested within the article element. A separate site footer can still appear outside the article and provide global navigation or contact details. Do not use an article footer merely to force content below the article with CSS.

    What belongs in footer HTML code, including contact details?

    Choose footer content according to scope:

    • Document scope: site name, copyright notice, global navigation, privacy links, accessibility information, and general contact details.
    • Article scope: author name, publication or update dates, categories, tags, licensing details, and article-specific related links.
    • Section scope: supporting information that applies only to that section, such as a section editor or a link to its complete archive.

    Keep the structure meaningful. Use paragraphs for short notices, lists for groups of links, and navigation markup for a distinct navigation region. Contact details can appear in an address element when they identify the relevant site, organization, or author. A footer supplies semantics and reading structure; it does not create columns, a sticky bar, a bottom alignment, or any other visual treatment without CSS.

  • Textarea: Markup, Initial Content, Value, and Sizing

    Textarea: Markup, Initial Content, Value, and Sizing

    A textarea creates a multiline text field for messages, comments, notes, and other longer entries. Its opening and closing tags surround the initial content, while the name attribute identifies the submitted field and the id connects it to a label and JavaScript.

    The text area HTML pattern also separates three related concepts: text placed between the tags, a placeholder hint, and the control’s current value. Each behaves differently in a form and in JavaScript.

    Create and label a textarea

    Give the control a unique id, then set the label’s for attribute to the same value. Add a name so the field can be included in form submission.

    <label for="message">Message</label>
    <textarea id="message" name="message" rows="5" cols="40"></textarea>

    The label makes the purpose clear and gives users a larger target for focusing the field. The matching for and id attributes establish that connection. The name becomes the field’s submission key, such as message.

    Unlike a void element such as input, a textarea requires both an opening tag and a closing tag. The content belongs between those tags, even when the field starts empty. A field without a name can still be read with JavaScript, but its value is not included in a normal form submission.

    Initial content versus placeholder text

    To supply initial text, write it between the opening and closing textarea tags:

    <textarea id="message" name="message" rows="5" cols="40">Please include your order number.</textarea>

    This text is the field’s initial value. It appears as real content, can be edited immediately, and is submitted if the user leaves it unchanged. Do not use a value attribute as the source of a textarea’s initial text. The content between the tags is the correct HTML mechanism.

    A placeholder is only a temporary instruction or example:

    <textarea id="message" name="message" placeholder="Describe the issue" rows="5" cols="40"></textarea>

    The placeholder disappears when the user types and is not submitted as the field’s value. It should not replace a visible label or carry essential information. Keep the element empty between its tags when you want a placeholder rather than initial content.

    Whitespace between the tags also becomes part of the initial content. Avoid unintended spaces or line breaks if the starting value must match an exact string.

    Read and set the HTML textarea value

    When a form is submitted, the browser sends the textarea’s current value under its name. For the earlier example, a field named message contributes a name-value pair similar to message=The user’s text. The exact encoding depends on the form’s method and encoding settings, but the submitted text comes from the current field value.

    JavaScript reads that current value through the element’s value property:

    const message = document.getElementById("message");
    const currentText = message.value;

    Use the same property to replace or append text:

    message.value = "A new starting message";
    message.value += "\nAdditional details";

    The value property changes as the user types. It therefore represents the current, editable content, not necessarily the text originally written in the HTML. If you need the original markup-defined value, defaultValue represents that starting value. Calling a form reset restores the textarea to its default value.

    Size and resize the control with rows and cols

    The rows and cols attributes set the textarea’s approximate starting dimensions:

    <textarea name="message" rows="8" cols="60"></textarea>

    • rows indicates the approximate number of visible text lines.
    • cols indicates the approximate character width.
    • Neither attribute limits how much text the user can enter.

    Font choice, browser rendering, and CSS can affect the displayed size. For consistent layouts, set the control’s width and height in an external stylesheet rather than relying only on cols and rows. Those HTML attributes still provide useful fallback dimensions and communicate the intended editing area.

    Textareas are commonly resizable by dragging their corner. Set the CSS resize property to vertical when users may change the height but not the width, or to none when resizing should be disabled. Add a maxlength attribute when the field also needs a character limit; sizing alone does not enforce one.

  • HTML nav: How to Mark Up Page Navigation

    HTML nav: How to Mark Up Page Navigation

    The HTML nav element identifies a major group of links that helps users move through a website or page. Use it for primary site navigation, a section menu, breadcrumbs, or an in-page table of contents when the group represents a meaningful navigation landmark.

    The element describes the purpose of a link group, not its visual design. You can style the same semantic structure as a horizontal menu, sidebar, drawer, or mobile navigation without changing the markup.

    What the HTML nav tag Represents

    The HTML nav tag creates a navigation landmark for a collection of important links. Assistive technology can expose that landmark so people can move directly to major navigation areas instead of reading every link in document order.

    Major navigation usually supports a broad movement task, such as moving between the main sections of a site, browsing categories, or jumping between the sections of a long article. Common examples include:

    • A site-wide primary menu with links such as Home, Products, and Contact
    • A section menu for related pages within a documentation or learning area
    • An in-page menu linking to headings in a long article
    • A breadcrumb trail showing the current page’s position in a hierarchy

    Not every group of links needs a nav landmark. An isolated “Read more” link, a pair of related actions, or a small set of footer links may not represent major navigation. Avoid wrapping every isolated link or footer link group in nav without considering its navigational significance. Too many landmarks make page structure harder to scan, especially for people navigating by landmarks.

    How to Mark Up a Primary HTML Navigation Menu

    Place the primary menu near the site header when it represents the main route through the site. A list gives the links a clear group structure, while each anchor provides a specific destination. This complete example contains the nav element, an unordered list, and four links:

    <nav aria-label=”Primary”>

      <ul>

        <li><a href=”/”>Home</a></li>

        <li><a href=”/services/”>Services</a></li>

        <li><a href=”/about/”>About</a></li>

        <li><a href=”/contact/”>Contact</a></li>

      </ul>

    </nav>

    The aria-label gives this landmark a concise name. Keep link text specific and meaningful when read on its own. The nav element does not require a list, but lists are often the clearest choice for a menu because they express that the links belong to one set. CSS can control spacing, alignment, dropdown behavior, and responsive presentation separately from this structure.

    When to Use More Than One nav Element in HTML

    A page can contain several navigation landmarks when each one serves a distinct purpose. For example, a header may contain the primary site menu, while the article contains an in-page contents menu. Both are valid because they help users navigate different scopes.

    Give each landmark a distinct accessible name when more than one appears on the page. For example, use Primary navigation, Section navigation, or On this page rather than assigning the same generic label to every region:

    • Primary navigation: links to the main areas of the website
    • Section navigation: links to related pages within the current area
    • On this page: links to headings in the current document

    A visible heading or text label can also distinguish navigation regions for sighted readers. When the label needs to name the landmark for assistive technology, provide an accessible name such as an appropriate aria-label. Distinct names make landmark lists useful instead of forcing users to inspect each region.

    How Lists, Labels, and Page Structure Clarify Navigation

    Use one list item for each navigation destination, and keep the hierarchy aligned with the information architecture. A nested list can represent a submenu under a parent category. The visual design may hide or reveal that submenu, but the underlying relationships should remain understandable.

    Keep navigation links in a logical order, starting with the most important or frequently used destinations. Use consistent wording between the menu label and the destination heading. For an in-page menu, link text such as Features or Pricing is clearer than repeated labels such as Read more.

    In the phrase HTML navigation, the important distinction is semantic grouping: nav identifies a meaningful route through content, while lists organize the links within that route. Use both when they clarify the page, and leave smaller link groups as ordinary content when adding a landmark would not help users.