Category: Web Development

  • Get Object Keys in JavaScript: Find, Read, and Iterate

    Get Object Keys in JavaScript: Find, Read, and Iterate

    To get object keys in JavaScript, use JavaScript Object.keys() to list an object’s own enumerable string keys. Use bracket notation to read a property whose name is stored in a variable, and use Object.entries() to process keys and values together.

    Finding a key and accessing a property are separate operations. Object.keys() discovers available names; bracket access retrieves a value after you choose a name. The methods below focus on own properties, so inherited data does not silently enter your results.

    Get object keys in JavaScript with Object.keys()

    Object.keys(source) returns a new array containing the object’s own enumerable property names that are strings. It excludes inherited properties, non-enumerable properties, and symbols. The result is shallow: it lists keys on the source object, not keys inside nested objects.

    • const profile = { name: “Mina”, role: “editor” };
    • Object.keys(profile) returns [“name”, “role”].

    The returned array is useful for displaying field names, checking whether an object has any enumerable data, or building a controlled iteration. An object with no own enumerable string properties produces an empty array.

    Get a key from an object in JavaScript, then read its value

    When you already know a key, do not search the key array to read its value. Dot notation works for a known identifier-like property name, such as profile.name. Bracket notation evaluates an expression, making it the required form for dynamic names, such as profile[field]. It also handles names that are not valid identifiers, including “display-name”.

    const field = “role”; const value = profile[field]; stores “editor” in value. In contrast, profile.field looks for a property literally named field; it does not use the variable’s contents. Reading a missing property returns undefined, whether the missing name is supplied with dot or bracket notation.

    Use JavaScript Object.keys(), Object.values(), and Object.entries()

    JavaScript Object.keys, Object.values(), and Object.entries() use the same selection rule: they include an object’s own enumerable string-keyed properties. They differ in what each returns:

    • Object.keys(profile) returns an array of property names.
    • Object.values(profile) returns the corresponding values, without their names.
    • Object.entries(profile) returns pairs such as [“name”, “Mina”].

    Use Object.values() when only the data matters. Use Object.entries() when each operation needs both the property name and its value:

    for (const [key, value] of Object.entries(profile)) { console.log(key, value); }

    This pattern avoids a second lookup and works naturally with destructuring. It iterates only own enumerable string keys, matching the behavior of Object.keys().

    Check own, symbol, and inherited keys with hasOwn and Reflect.ownKeys()

    Object.hasOwn(object, key) checks whether a property belongs directly to the object. It returns true for an own property even when that property is non-enumerable, and false for an inherited property. It is safer and clearer than calling a possibly overridden object.hasOwnProperty() method.

    • const parent = { inherited: true };
    • const record = Object.create(parent); record.visible = true;
    • Object.hasOwn(record, “visible”) returns true.
    • Object.hasOwn(record, “inherited”) returns false.

    Reflect.ownKeys(record) returns every own property key, including enumerable and non-enumerable string keys plus symbol keys. This is broader than Object.keys(), Object.values(), and Object.entries(), which omit symbols and non-enumerable properties. Use Object.getOwnPropertyNames() for all own string keys, or Object.getOwnPropertySymbols() for own symbol keys.

    A for…in loop is different: it visits enumerable string keys from the object and its prototype chain. If you use one, guard each key with Object.hasOwn(record, key). For own enumerable data, Object.keys() or Object.entries() is usually clearer.

  • How to Check for an Empty Object in JavaScript

    How to Check for an Empty Object in JavaScript

    To check for an empty object in JavaScript, first define empty as “no own enumerable string-keyed properties.” For a value already known to be a plain object, Object.keys(obj).length === 0 is the direct test. To safely check an empty object in JavaScript when input may be null or another type, add guards before calling Object.keys().

    A JavaScript empty object can still have inherited, symbol, or non-enumerable properties, so the result depends on which properties your application considers.

    How to check for an empty object in JavaScript with Object.keys(obj).length === 0

    Object.keys() returns an array containing an object’s own enumerable string keys. An object literal with no such keys produces an empty array:

    const value = {};
    Object.keys(value).length === 0; // true

    An object with an own enumerable property produces a nonzero length:

    const value = { name: “Ada” };
    Object.keys(value).length === 0; // false

    When the input is expected to be an object but may be null, use a type and null guard:

    const isEmpty = value =>
      value !== null &&
      typeof value === “object” &&
      Object.keys(value).length === 0;

    This condition also returns true for arrays, dates, maps, sets, and some class instances that have no enumerable own string properties. Use the stricter plain-object check below when the value’s type is not already controlled.

    Guard an empty JavaScript object check against null, arrays, Map, Set, Date, and class instances

    typeof null is “object”, but Object.keys(null) throws a TypeError. Check for null before the type test. Arrays also have object types, so a separate array check or a plain-object prototype check is needed.

    This function accepts object literals and objects created with a null prototype, while rejecting arrays and built-in or custom instance types:

    const isEmptyPlainObject = value =>
      value !== null &&
      typeof value === “object” &&
      (Object.getPrototypeOf(value) === Object.prototype ||
       Object.getPrototypeOf(value) === null) &&
      Object.keys(value).length === 0;

    An array should usually be tested with value.length === 0. A Map and a Set store data in internal collection slots, so use map.size === 0 or set.size === 0. A Date is a date value rather than an empty record. A class instance may have no own fields while still representing a meaningful domain object; test its required fields or use an instanceof check before applying an emptiness rule.

    What does a JavaScript empty object mean for own, inherited, symbol, and non-enumerable properties?

    Object.keys() counts only own, enumerable, string-named properties. Each category changes the result:

    • Own properties: properties stored directly on the object. Enumerable own properties appear in Object.keys().
    • Inherited properties: properties found on the object’s prototype. They do not appear in Object.keys(), and this is normally desirable for configuration or data objects.
    • Symbol properties: own symbol-keyed properties are not returned by Object.keys(), even when they are enumerable.
    • Non-enumerable properties: own string or symbol properties marked non-enumerable are also excluded.

    For example, an object can have hidden data while appearing empty to Object.keys():

    const value = {};
    Object.defineProperty(value, “id”, { value: 7 });
    Object.keys(value).length === 0; // true

    To count all own string and symbol keys, including non-enumerable keys, use Reflect.ownKeys(value).length === 0. Object.getOwnPropertyNames() includes all own string keys, while Object.getOwnPropertySymbols() returns own symbol keys. A for…in loop is not equivalent to Object.keys() because it can include inherited enumerable properties.

    Choose a definition of emptiness when checking whether an object is empty in JavaScript

    • For a plain data object, define empty as having no own enumerable string keys and use the guarded Object.keys(value).length === 0 test.
    • For an object where symbols or non-enumerable metadata matter, use Reflect.ownKeys(value).length === 0 after validating the value’s type.
    • For collections, use their native size or length: Map.size, Set.size, or array length.
    • For inherited settings, decide explicitly whether the prototype contributes data. Avoid treating inherited properties as own record fields by accident.

    Do not use JSON.stringify(value) === “{}” as a universal emptiness test. Serialization omits symbols, non-enumerable properties, and several values that do not serialize as ordinary object keys. It also says nothing about whether the value is a plain object, so property inspection and type validation are more reliable.

  • JavaScript Not-Equal Operators: !== vs !=

    JavaScript Not-Equal Operators: !== vs !=

    Use !== for most not-equal operators in JavaScript. It performs a strict comparison, so values must have the same type and value to be considered equal. Use != only when you deliberately want JavaScript to convert values before comparing them.

    These operators can produce different results for the same pair. Choosing the right one prevents unexpected matches between numbers, strings, booleans, and nullish values.

    JavaScript Not-Equal Operators: Choose !== or !=

    !== is the strict inequality operator. It is the negation of strict equality: a !== b produces the same result as !(a === b). It returns true when the operands have different types or different values.

    != is the loose inequality operator. It is the negation of loose equality: a != b produces the same result as !(a == b). Before deciding whether values differ, JavaScript may convert one operand to another type.

    For predictable JavaScript not-equal comparisons, prefer !==. Reserve != for cases where that conversion is an intentional part of the condition.

    How does JavaScript strict inequality with !== work?

    Strict inequality checks type and value without coercion. Two numbers with different values are not equal, and a number is not strictly equal to a string containing the same digits.

    • 7 !== 4 is true because the number values differ.
    • 7 !== “7” is true because one operand is a number and the other is a string.
    • “ready” !== “ready” is false because both operands are the same string.
    • null !== undefined is true because they are different types.

    Strict inequality also follows JavaScript’s strict equality rules for special numeric values. In particular, NaN !== NaN is true, while 0 !== -0 is false.

    How does JavaScript not-equal comparison with != handle type coercion?

    Loose inequality applies the abstract equality rules before returning the opposite result. A numeric string can be converted to a number, and boolean values can be converted to numbers. This means operands that look different in source code may compare as equal.

    • 7 != “7” is false. The string is converted to the number 7.
    • 0 != false is false. The boolean is converted to 0.
    • “” != 0 is false. The empty string is converted to 0.
    • null != undefined is false. These two values are treated as equal by loose equality.

    Coercion can be useful when an input is expected to contain a numeric or boolean representation. It can also hide invalid data, so a loose condition should document or clearly reflect that intent.

    Which results change for numbers, strings, null, and NaN?

    Which value pairs make != and !== disagree?

    The operators disagree whenever loose equality converts the operands into matching values or applies its special nullish rule.

    • 5 and “5”: 5 != “5” is false, but 5 !== “5” is true.
    • 0 and false: 0 != false is false, but 0 !== false is true.
    • null and undefined: null != undefined is false, but null !== undefined is true.

    For ordinary unequal values such as 3 and 8, both operators return true. The difference appears when types or special values affect the comparison.

    Why does NaN need an explicit check?

    NaN means “Not-a-Number,” but it is still a number value according to typeof. It is not equal to itself, so both NaN != NaN and NaN !== NaN return true. Testing whether two values differ does not identify NaN specifically.

    Use Number.isNaN(value) for an explicit check. Unlike the global isNaN() function, Number.isNaN() does not first coerce unrelated values such as strings.

    How do you write clear JavaScript not-equal checks?

    • Use value !== expected when both type and value must match.
    • Use typeof value !== “string” when rejecting values of a particular type.
    • Use value !== null when only the literal null should be excluded.
    • Use value != null only when intentionally treating both null and undefined as missing.
    • Convert input explicitly when conversion is required, then compare strictly: Number(input) !== 10.

    In most not-equal checks in JS, !== communicates the intended rule directly and avoids implicit conversion. Choose != only when its coercive behavior is known, tested, and desirable.

  • JavaScript filter: Array.filter() With Practical Examples

    JavaScript filter: Array.filter() With Practical Examples

    JavaScript filter keeps the elements in an array that satisfy a condition. Its main method, Array.filter(), calls a callback for each existing element and returns a new array containing every element whose callback result is truthy.

    Use it for collections with zero, one, or many matches. The original array remains unchanged, so the method is suitable for creating filtered views of data without removing elements from the source.

    How JavaScript filter works

    The JavaScript filter function receives up to three callback arguments: the current element, its index, and the complete array. Most callbacks use only the element:

    Example: const numbers = [3, 8, 12, 15]; const multiples = numbers.filter((element) => element % 3 === 0);

    The returned value is [3, 12, 15]. To access all callback arguments, use this form:

    Example: const firstHalf = numbers.filter((element, index, array) => index < array.length / 2 && element > 5);

    A callback does not need to return the words true or false. Any truthy result keeps the element; false, 0, “”, null, and undefined exclude it. Returning a boolean expression makes the intended rule clearest.

    filter() does not mutate the original array. It creates a new array, although object elements inside it still reference the same objects. If no elements pass the condition, the result is an empty array: [].

    How does the JavaScript filter function select numbers and strings?

    For numbers, write a predicate that describes the allowed value. This example keeps values at least 10:

    Example: const scores = [7, 10, 14, 18]; const passing = scores.filter(score => score >= 10);

    The result is [10, 14, 18], while scores is unchanged. The same pattern works with strings. Combine typeof with a text condition when an array may contain different data types:

    Example: const values = [“JavaScript”, 42, “filter”, null]; const words = values.filter(value => typeof value === “string” && value.length > 5);

    This returns [“JavaScript”, “filter”]. The filter function JavaScript developers use can therefore select by type, length, range, pattern, or any other callback condition.

    How JavaScript Array.filter() handles objects, missing values, and multiple conditions

    For objects, inspect a property inside the callback. This example keeps active users:

    Example: const users = [{ name: “Ana”, active: true }, { name: “Bo”, active: false }, { name: “Cy”, active: true }]; const activeUsers = users.filter(user => user.active === true);

    The result contains Ana and Cy. A missing property evaluates to undefined, so an explicit comparison such as user.active === true safely excludes an object without an active property.

    Filter out missing or invalid values by checking the value before using it:

    Example: const values = [10, undefined, 25, null, 40]; const validNumbers = values.filter(value => typeof value === “number”);

    The result is [10, 25, 40]. For a sparse array with genuinely empty slots, filter() skips those unassigned slots rather than calling the callback for them.

    Use logical operators for compound conditions. This example keeps in-stock products costing no more than 50:

    Example: const products = [{ name: “Pen”, price: 3, inStock: true }, { name: “Bag”, price: 45, inStock: false }, { name: “Lamp”, price: 38, inStock: true }]; const affordable = products.filter(product => product.inStock && product.price <= 50);

    The && operator requires both conditions to pass. Use || when either condition is acceptable, such as selecting products in the “office” or “school” category.

    When should you use the filter function in JavaScript instead of find or map?

    Choose filter() when the required result is an array containing every match. Its result always has array shape, including an empty array when nothing matches.

    Choose find() when you need one element: specifically, the first match. It returns that element or undefined, not an array. Do not use filter() when a single first match is the required result.

    Choose map() when every element should produce a transformed value. It normally returns an array with the same number of elements, whereas filter() removes elements that fail its predicate.

  • Python Web Server: Run a Simple HTTP Server Locally

    Python Web Server: Run a Simple HTTP Server Locally

    Run a Python web server from the directory you want to share with this command:

    python -m http.server

    Python starts a simple HTTP server on port 8000. Open http://localhost:8000/ in a browser to view the directory contents. On systems where the launcher is named differently, use python3 -m http.server on macOS or Linux, or py -m http.server on Windows.

    Start a Python web server with python -m http.server (or python3/py)

    The command serves files from your current working directory: the folder selected in the terminal when you start the process. For example, to serve a site stored in a folder named website:

    cd website

    python -m http.server

    Then visit http://localhost:8000/. If the directory contains an index.html file, the server displays it as the default page. Otherwise, the built-in handler shows a directory listing that lets you open individual files.

    This simple HTTP server with Python is useful for previewing static HTML, CSS, JavaScript, images, and other files on your own computer. It does not execute server-side Python, PHP, or JavaScript application code.

    Choose the directory, port, and bind address with –directory and –bind

    Use –directory to serve a folder without changing the terminal’s working directory:

    python -m http.server –directory ./website

    A relative path starts from the current working directory. You can also provide an absolute path. Combine it with a port number when 8000 is already in use:

    python -m http.server 9000 –directory ./website

    Open http://localhost:9000/ for that server. A port conflict means another process is already listening on the selected port. Stop that process or choose another unused port, such as 9000 or 8080. The same options work with python3 and py:

    py -m http.server 9000 –directory .\website

    By default, the server can listen beyond the local machine, depending on the platform and network configuration. Use –bind 127.0.0.1 to restrict access to the computer running the server:

    python -m http.server 8000 –directory ./website –bind 127.0.0.1

    To make the server reachable from other devices on the same network, bind it to the computer’s LAN address or use –bind 0.0.0.0, then browse to the host computer’s local IP address and port. Only expose files you intend to share.

    Open http://localhost:8000, read request logs, and stop the server

    With the default command running, browse to http://localhost:8000/. Each browser request appears in the terminal, typically with the client address, method, path, protocol, and status code:

    127.0.0.1 – – “GET /index.html HTTP/1.1” 200 –

    A 200 status means the file was served successfully. A 404 indicates that the requested path was not found. Browsers may make additional requests for stylesheets, scripts, icons, or source maps, so several log lines can appear for one page load.

    Keep the terminal process running while you use the server. Press Ctrl+C to stop it cleanly. Refreshing the browser after changing a file displays the updated version, although browser caching can sometimes require a hard refresh.

    Create a simple Python server with a custom handler—and know its limits

    Use a custom handler when you need a fixed response or a small change to request behavior. Save the following as server.py:

    from http.server import BaseHTTPRequestHandler, HTTPServer

    class Handler(BaseHTTPRequestHandler):

    def do_GET(self):

    body = b”Hello from Python\n”

    self.send_response(200)

    self.send_header(“Content-Type”, “text/plain; charset=utf-8”)

    self.send_header(“Content-Length”, str(len(body)))

    self.end_headers()

    self.wfile.write(body)

    server = HTTPServer((“127.0.0.1”, 8000), Handler)

    server.serve_forever()

    Start it with python server.py, python3 server.py, or py server.py, then open http://localhost:8000/. This simple Python server responds to GET requests with plain text instead of serving files. You can add path checks, headers, or different response bodies inside do_GET.

    The built-in server is intended for local development, testing, and quick file sharing. It provides basic HTTP handling and request logging, but it is not a production application server: it lacks the routing, security controls, concurrency features, deployment tooling, and application framework integration required for a public service.

  • CSS Versions: CSS1, CSS2, and the CSS3 Release Timeline

    CSS Versions: CSS1, CSS2, and the CSS3 Release Timeline

    CSS versions are best understood as a standards timeline, not as a sequence of software packages. CSS1 became a W3C Recommendation on 17 December 1996, and CSS2 followed on 12 May 1998. After CSS2, the specification model changed: CSS3 was divided into separate modules that could advance at different speeds.

    That is why the phrase CSS3 release date is misleading. There is no single date when every feature associated with CSS3 became an official, finished standard.

    CSS versions: CSS1 (17 December 1996) and CSS2 (12 May 1998)

    The major early CSS milestones are:

    • CSS1 — 17 December 1996: The first CSS specification to become a W3C Recommendation. It established core styling features such as fonts, colors, text properties, margins, padding, borders, and basic selectors.
    • CSS2 — 12 May 1998: The second major specification expanded CSS with positioning, media types, generated content, layers, and support for aural presentation.
    • CSS2.1 — 7 June 2011: A revised version of CSS2 that removed, clarified, or corrected features based on implementation experience. It is separate from CSS3.

    CSS1 and CSS2 each represented a broad, coordinated specification. That approach worked for foundational features, but it made the standard difficult to update when different areas were ready at different times.

    When was CSS3 released, and why is there no single date?

    If you ask, “when was CSS3 released,” the accurate answer is that CSS3 did not arrive as one monolithic release. After CSS2, the W3C moved toward a modular structure. Work on early CSS3 modules began around the end of the 1990s, and each module followed its own development and publication path.

    For example, Selectors Level 3, Color Level 3, and Media Queries Level 3 were developed and standardized separately. They did not necessarily reach Recommendation status at the same time, and browser support often appeared before a module was fully standardized.

    Consequently, a date attached to one CSS3 module cannot serve as the release date for all CSS3-era features. Some modules became Recommendations, while others remained working drafts, were revised, or moved into newer levels.

    How did CSS3 modules and levels change the standards model?

    A module covers one area of CSS. Examples include Selectors, Color, Backgrounds and Borders, Transforms, Grid Layout, and Media Queries. Each area can be edited, tested, implemented, and standardized without waiting for every other CSS feature to be complete.

    A module’s level identifies its revision or scope. Selectors Level 3 and Selectors Level 4 are successive versions of the Selectors module. The level number does not describe a single global CSS release. One module can be at Level 4 while another remains at Level 3 or advances to Level 5.

    This structure also separates stable features from proposals and revisions. A module may progress from a working draft to a candidate stage and then to a Recommendation, while another module continues through design changes. The standards process therefore reflects the maturity of individual features rather than one all-or-nothing CSS launch.

    What do modern CSS version labels and snapshots mean?

    “CSS3” remains useful as a historical label for the modular era, especially when discussing features such as Flexbox, Grid, transitions, and advanced selectors. It is not a current, unified version number. “CSS4” is likewise usually informal shorthand unless it names a specific module, such as Selectors Level 4 or Color Level 4.

    Modern CSS snapshots provide a different kind of reference. A snapshot collects specifications and feature levels considered part of the platform at a particular point in time. It is a status picture, not a new CSS version that replaces everything before it.

    For current implementation details, identify the individual module and feature. Browser support is tracked feature by feature because specifications, levels, and implementations continue to progress independently.

  • 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.