🛋️

Html

 

Void element

A void element is an element whose content model never allows it to have contents under any circumstances. Void elements can have attributes. The following is a complete list of the void elements in HTML : area , base, br, col, command, embed, hr, img, input, keygen, link, meta, param, source, track, wbr.

Data Attributes

data-* attributes enable us to add additional information to standard, semantic HTML elements without resorting to non-standard attributes or extra properties on the DOM.
HTML
<article
  id="electric-cars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
  …
</article>
Access values in JS
JavaScript
const article = document.querySelector("#electric-cars");
// The following would also work:
// const article = document.getElementById("electric-cars")

article.dataset.columns; // "3"
article.dataset.indexNumber; // "12314"
article.dataset.parent; // "cars"
Access values in CSS
CSS
article::before {
  content: attr(data-parent);
}

article[data-columns="3"] {
  width: 400px;
}
article[data-columns="4"] {
  width: 600px;
}

From

Input
HTML
<label for="color">What is your favorite color</label>
<input type="text" id="color" name="color"> // when you submit the form, this name is included in the request (color=XXX)
<input type="checkbox" id="subscribe" name="subscribe" value="web.dev">
<label for="subscribe">Subscribe to web.dev?</label>
Options
HTML
<label for="color">Color</label>
<select id="color" name="color">
  <option value="orange" selected>Orange</option> // set pre-select one option
  <option value="pink">Pink</option>
</select>
fieldset - group form controls
HTML
<fieldset>
    <legend>What is your favorite web technology</legend>

    <label for="html">HTML</label>
    <input type="radio" name="webfeature" value="html" id="html">

    <label for="css">CSS</label>
    <input type="radio" name="webfeature" value="css" id="css">
</fieldset>
đź’ˇ
Every <button> element inside a form works as a Submit button by default. However, when you don't want this behavior (e.g. when using a <button> to toggle visibility of a password field), you can add type="button" to the <button> to disable the default Submit behavior.
How can you submit a form?
Clicking a <button> element, using the Enter key, clicking an <input> element with type='submit'.
 
Validation
Attributes
  • required
  • minlength
  • pattern="[a-z]{2,20}”
Change the default error message
JavaScript
const nameInput = document.querySelector('[name="name"]');
nameInput.addEventListener('invalid', () => {
    nameInput.setCustomValidity('Please enter your name.');
 });
Ensure users comprehend the validation rules by connecting the form control to an element that explains them. To achieve this, add an aria-describedby attribute to the element, with the id of the form.
HTML
<label for="password">Password (required)</label>
<input required minlength="8" type="password" id="password"
  name="password" aria-describedby="password-minlength">
<div id="password-minlength">Enter at least eight characters</div>
Css pseudo classes related to input fields::
:invalid (Invalid form fields are already marked as :invalid  before user interaction, which may confuse users)
:user-invalid (The styles are only applied after user interaction, this feature is in experiments so only firefox support it)
:required
:valid
:autofill
 
Check evether a field in a form is validated ele.validity.valid
 
HTML
<form>
      <div>
        <label for="name">Name</label>
        <input required minlength="10" type="text" id="name" name="name" aria-describedby="name-validation">
        <span id="name-validation" aria-live="assertive" class="validation-message"></span>
/* use aria-live="assertive" for the error message. ARIA live regions announce an error to screen reader users the moment the error is shown. */
      </div>
      <button>Save</button>
    </form>

Image/Picture

The <picture> element provides image versions for different display/device scenarios by containing zero or more <source> elements and one <img> element. The browser selects the most suitable child <source> element, or if none match, it selects the URL in the src attribute of the <img> element. The selected image is then displayed in the space occupied by the <img> element.
HTML
<picture>
 <!-- Some modern image formats that have higher performance but also require compatibility.-->
  <source src="image.avif" type="image/avif">
  <source src="image.jxl" type="image/jxl">
  <source src="image.webp" type="image/webp">

   <!-- Provide default for compatibility -->
  <img src="image.jpg" type="image/jpeg">
</picture>
 
Provide different resolutions for different devices.
HTML
<img src='illustration-small.png'
       srcset='images/illustration-small.png 1x,
               images/illustration-big.png 2x'
   >
The 1x and 2x in the srcset above are pixel density descriptors, which means:
  • When the screen's dpr = 1, use the image images/illustration-small.png.
  • When the screen's dpr = 2, use the image images/illustration-big.png.
  • If the srcset syntax is not supported, src='illustration-small.png' will be the final fallback plan.
 
Consider the device width
HTML
<img 
        sizes = “(min-width: 600px) 600px, 300px" 
        src = "photo.png" 
        srcset = “[email protected] 300w,
                       [email protected] 600w,
                       [email protected] 1200w,
>
The meaning of sizes = "(min-width: 600px) 600px, 300px is:
  1. If the current CSS pixel width of the screen is greater than or equal to 600px, then the CSS width of the image is 600px.
  1. Otherwise, the CSS width of the image is 300px.

Unfrequently used HTML5 tags

details/summary

HTML
<style> 
/*
Change the styles according to the detials open/close status
*/
details {
    border: 1px solid #aaa;
    border-radius: 4px;
    padding: 0.5em 0.5em 0;
}

summary {
    font-weight: bold;
    margin: -0.5em -0.5em 0;
    padding: 0.5em;
}

details[open] {
    padding: 0.5em;
}

details[open] summary {
    border-bottom: 1px solid #aaa;
    margin-bottom: 0.5em;
}
</style>
<details>
    <summary>I have keys but no doors. I have space but no room. 
						You can enter but can’t leave. What am I?</summary>
    A keyboard.
</details>

<script>
// The toggle event fires when the open/closed state of a <details> element is toggled.

addEventListener('toggle', (event) => {});

ontoggle = (event) => { };
</script>

datalist

HTML
<label for="ice-cream-choice">Choose a flavor:</label>
<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice">

<datalist id="ice-cream-flavors">
    <option value="Chocolate">
    <option value="Coconut">
    <option value="Mint">
    <option value="Strawberry">
    <option value="Vanilla">
</datalist>
 

dialog

  • Natively support focus trapping
  • Not support Light-dismiss functionality. Clicking outside of the popover area will close the popover and return focus.
HTML
<!-- A modal dialog containing a form -->
<dialog id="favDialog">
  <form>
    <p>
      <label>Favorite animal:
        <select>
          <option value="default">Choose…</option>
          <option>Brine shrimp</option>
          <option>Red panda</option>
          <option>Spider monkey</option>
        </select>
      </label>
    </p>
    <div>
      <button value="cancel" formmethod="dialog">Cancel</button>
      <button id="confirmBtn" value="default">Confirm</button>
    </div>
  </form>
</dialog>
<p>
  <button id="showDialog">Show the dialog</button>
</p>
<output></output>

<script>
	const showButton = document.getElementById('showDialog');
	const favDialog = document.getElementById('favDialog');
	const outputBox = document.querySelector('output');
	const selectEl = favDialog.querySelector('select');
	const confirmBtn = favDialog.querySelector('#confirmBtn');
	
	// "Show the dialog" button opens the <dialog> modally
	showButton.addEventListener('click', () => {
	  favDialog.showModal();
	});
	
	// "Favorite animal" input sets the value of the submit button
	selectEl.addEventListener('change', (e) => {
	  confirmBtn.value = selectEl.value;
	});
	
	// "Cancel" button closes the dialog without submitting because of [formmethod="dialog"], triggering a close event.
	favDialog.addEventListener('close', (e) => {
	  outputBox.value = favDialog.returnValue === 'default' ? "No return value." : `ReturnValue: ${favDialog.returnValue}.`; // Have to check for "default" rather than empty string
	});
	
	// Prevent the "confirm" button from the default behavior of submitting the form, and close the dialog with the `close()` method, which triggers the "close" event.
	confirmBtn.addEventListener('click', (event) => {
	  event.preventDefault(); // We don't want to submit this fake form
	  favDialog.close(selectEl.value); // Have to send the select box value here.
	});
</script>

popover

Popovers are great when you want to position an alert, modal, or notification based on the viewport. But popovers are also useful for menus, tooltips, and other elements that need to be positioned relative to other elements.
  • Light-dismiss functionality. Clicking outside of the popover area will close the popover and return focus.
  • Accessible keyboard bindings. Hitting the esc key will close the popover and return focus.
  • Promotion to the top layer: don’t have to futz around with z-index.
HTML
<button popovertarget="my-popover"> Open Popover </button>

<div id="my-popover" popover={manual|auto}>
	<button class="close-btn" popovertarget="my-popover" popovertargetaction="hide">
    <span aria-hidden=”true”>❌</span>
    <span class="sr-only">Close</span>
  </button>
  <p>I am a popover with more information.<p>
</div>


<style>
	#my-popover::backdrop {
	  background: rgb(190 190 190 / 50%);
	}
</style>
Â