I may have been stuck in xml model or several years ago but in the Uni course I learned that a HTML5 document doesn't validate if you close self-closing elements. You should write <img src="" alt="">,
<br>,
<hr>
etc. and not <br/>
and so on.
Here's the W3C HTML5 validator: https://validator.w3.org/nu/#textarea. You can also add an extension to your code editor.
Also, the closing tag may be omitted if a block element follows, for instance:
<p>Some text added
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
is valid.
Confusing, eh!
I'm taking w3schools HTML course as a refresher and I learned a few things along the way.
I knew about blockquote but not sure about the other two.
Quote from another source:
Short inline quote:
Indicate the title of a work:
td stands for table data! th (table header) and tr (table row) were clear to me but I always wondered why a table cell was written "td". Now I can properly read the code in my head haha
In the img tag, prefer using style attribute with width and height properties inside rather than width and height attributes. style attribute takes precedence over the style defined in the linked CSS file (for instance max-width: 100%;) or at the HTML page level, but width and height attributes come second.
W3Schools recommends to always specify the width and height of an image. If not, the web page might flicker while the image loads.
This element is new to me. Inside you can define a list of images to display acording to the screen size, so to save bandwith and cover different format supporting from the browsers. It should always ends with an img tag. For instance (from W3Schools):
<picture>
<source media="(min-width: 650px)" srcset="img_food.jpg">
<source media="(min-width: 465px)" srcset="img_car.jpg">
<img src="img_girl.jpg" style="width:auto;">
</picture>
Can't always remember of dl (description list) with dt (term) and a dd (description), so now it's somewhere on this blog.
Also, it's good to now that there's a type attribute for ordered list (ol) to specify the type of the list item marker:
As well as a start attribute to chose from which number to start.
iframe stand for inline frame. It is used to embed another document in current document (just like a Youtube video for instance). Don't forget title attribute for screen readers. Default display will add borders so make sure you remove them with CSS or style attribute.
An iframe can be the target of a link, just refer to it with it's name: (example from W3Schools):
<iframe src="demo_iframe.htm" name="iframe_a" title="Iframe Example"></iframe>
<p><a href="https://www.w3schools.com" target="iframe_a">W3Schools.com</a></p>
Don't forget to let the user know JavaScript is needed for this or this functionnality with noscript tag:
<noscript>Sorry but the game relies on JavaScript. Have a look at your browser's settings if you wish to play it.</noscript>
From W3Schools.
Landmarks define some parts of the page to jump to with the help of a screen reader #accessibility
A section can include article and an article section, depends of the content.
A header can be found in several zones in an HTML document except in a footer, address or header element.
A footer is also repeatable in the HTML document.
Note that a button element should be used for any interaction that performs an action on the current page. The a element should be used for any interaction that navigates to another view.
kbd stands for keyboard inuput. Default browser's display is monospace font.
Some web servers (Apache, Unix) are case sensitive about file names: "london.jpg" cannot be accessed as "London.jpg".
Other web servers (Microsoft, IIS) are not case sensitive: "london.jpg" can be accessed as "London.jpg".
Nesting time or duration information into a time element is useful for any automatic reading of a page, from a search engine for instance.
I'll be celebrating my birthday on <time datetime="2024-09-21T20:00">September 21<sup>st</sup></time> for <time datetime="PT2H30M">2h30m</time>.
Forms are inevitable on a web journey. Here are some commented examples to understand each component
Table of contents:
Let's take this search field form (from How to transfigure wireframes into HTML by Lara Aigmüller) as an example.
form tag -> to open an area in the document where the user can provide information
action attribute -> indicates an URL where the form data should be sent. If omitted, it defaults to current page.
role attribute -> for accessibility purposes (value is search to identify search functionnality)
label tag -> to help associate the text for an input element with the input element itself (clicking on the text will select the corresponding button; helpful for assistive technologies)
for attribute -> association method with an input id where values are the same. Another method could be:
<label>
<input type="search" id="search-input" placeholder="Search…" name="q" />
Search articles
</label>
input tag -> allows several ways to collect data
type attribute -> many possible values, see below
id attribute -> the most important attribute in the universe. Used to identify specific HTML elements. Each id attribute's value must be unique from all other id values for the entire page.
placeholder attribute -> used to give people a hint about what kind of information to enter into an input but this is actually not a best-practice for accessibility (users can confuse the placeholder text with an actual input value).
name attribute -> value to represent the data being submitted, mandatory to be processed on the server-side. Helps grouping radio buttons (selecting one deselects the other - see survey form example).
value attribute -> initial value (for submit and button types: text that will display) - for instance ->
<form method="post" action="./contact">
<input id="name" type="text" name="name" value="" placeholder="Name" required>
<input id="email" type="email" name="email" value="" placeholder="Email" required>
<textarea id="message" rows="6" name="message" placeholder="Message" required></textarea>
<div data-sitekey="..."></div>
<button id="submit" name="submit" type="submit">Send email</button>
</form>
Let's take this contact form (from Bludit plugin) as an example.
form tag method attribute -> specifies how to send form-data
input tag required attribute -> data is mandatory to allow submission
div tag data-sitekey attribute -> I'll do some research on this topic later on. For now let's just say it's used to prevent spaming using CAPTCHA.
Question of the day: is there a "better" solution between button and input tag when type is submit? After some research I believe the answer is: no, functionnaly, it's identical. However, button elements are much easier to style and inner HTML content can be added. Note however that the first input element with a type of submit is automatically set to submit its nearest parent form element.
This is an example from FreeCodeCamp Responsive Web Design course:
<form action="https://freecatphotoapp.com/submit-cat-photo" target="_blank">
<fieldset>
<legend>Is your cat an indoor or outdoor cat?</legend>
<label>
<input id="indoor" type="radio" name="indoor-outdoor" value="indoor" checked> Indoor
</label>
<label>
<input id="outdoor" type="radio" name="indoor-outdoor" value="outdoor"> Outdoor
</label>
</fieldset>
<fieldset>
<legend>What's your cat's personality?</legend>
<input id="loving" type="checkbox" name="personality" value="loving" checked>
<label for="loving">Loving</label>
<input id="lazy" type="checkbox" name="personality" value="lazy">
<label for="lazy">Lazy</label>
<input id="energetic" type="checkbox" name="personality" value="energetic">
<label for="energetic">Energetic</label>
</fieldset>
<input type="text" name="catphotourl" placeholder="cat photo URL" required>
<button type="submit">Submit</button>
</form>
form tag, target attribute -> defines where to display the response after submitting the form. Default value is _self (ie current window)
fieldset tag -> used to group related inputs and labels together
legend tag -> acts as a caption for the content in the fieldset element
input tag
value atribute -> even if optionnal, it's best practice to include it with any checkboxes or radio buttons on the page. Otherwise, the form data would include name-value=on, which is not useful.
checked attribute -> force selection by default
button tag type attribute submit value -> note this is the default if the attribute is not specified for buttons associated with a <form>, or if the attribute is an empty or invalid value. button tag should always have a type attribute because different browsers may use different default types.
What type of input do you need?
min="2000-01-02"
)<input type="file" accept="image/*,.pdf">
<input type="button" value="Let's play!">
If type attribute is submit or image and if you want to proceed with a different action from the rest of the form with this input, use form+regularFormAttributeName to override form attributes for this specific button (ie formaction, formenctype, formmethod, formtarget, formnovalidate
<form action="/action_page.php">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
<input type="submit" formaction="/action_page2.php" formenctype="multipart/form-data" formmethod="post" formtarget="_blank" formnovalidate="formnovalidate" value="Submit as...">
</form>
Allow text edition on several lines. Use if you dare:
<textarea name="textarea" rows="10" cols="50">Please write here.</textarea>
Use for dropdown lists. Example from W3Schools:
<label for="cars">Choose a car:</label>
<select id="cars" name="cars" size="3" multiple>
<optgroup label="Swedish Cars">
<option value="volvo" selected>Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
selected attribute defines a pre-selected option.
size attribute defines the number of visible values
multiple attribute allow the selection of several options
Group options with optgroup element. Useful when lists are longs.
Specifies a list of pre-defined options for an input tag, showed depending on the user's input. Example from W3Schools:
<form action="/action_page.php">
<input list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
Represents the result of a calculation. Example from W3Schools:
<form action="/action_page.php" oninput="x.value=parseInt(a.value)+parseInt(b.value)">
0 <input type="range" id="a" name="a" value="50"> 100 +
<input type="number" id="b" name="b" value="50"> =
<output name="x" for="a b"></output>
<br/>
<input type="submit">
</form>
For form and input tags :valid and :invalid pseudo-classes
I recently discovered about Font Awesome and Unicode emojis. I thought: this a great way to have images without actually hosting them! As I'd like my projects to require a minimum of ressources that may suit my needs. But wait. I'd like these projects to also be as accessible as possible. How can you achieve that when this HTML element (for font awesome) and character (for Unicode emoji) are not HTML images (<img>) and therefore cannot have an alt attribute containing the relevant alternative text?
Let's dig this out!
Well, for Font Awesome, the answer is on their website, they have a dedicated section! It is beautifully sumed up on Upyouray11.com so I'll just try to sum up the sum up, so to have a reference somewhere on my own blog.
Hide it from assistive technologies with aria-hidden attribute, value true.
<i aria-hidden="true" class="fas fa-car"></i>
Hide the icon itself but indicate the link purpose (menu, home, cart...) with aria-label attribute on the action HTML element
<a href="/" aria-label="Home">
<i aria-hidden="true" class="fas fa-home"></i>
</a>
Hide the alternative text in a span element via CSS so it's dedicated to assistive technologies
HTML would be
<i aria-hidden="true" class="fas fa-plant" title="Vegetarian"></i> <span class="screen-reader-only">Vegetarian</span>
Note that we are adding a title attribute to help sighted mouse users
CSS would be
.screen-reader-only { position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden; }
Hide it from assistive technologies with aria-hidden attribute, value true in an additionnal span element:
<span aria-hidden="true">📖</span>
Nest the emoji into a span element and give it a role attribute, value img and the alternative text in aria-label attribute's value:
<span role="img" aria-label="open book">📖</span>
Now, let's apply this in this blog's contents!
Une autre chose avec laquelle j'ai un peu lutté, c'est de mettre deux éléments l'un en-dessous de l'autre (<nav> et <main>) sans que le texte présent dans <main> passe sous la barre de <nav> qui a un positionnement forcé.
Fragment de la page html sur laquelle je travaille :
<body>
<nav>
nav bar
</nav>
<main>
<section>
<h2>section 1</h2>
<p>Ut consectetur eros efficitur, convallis tortor ut, placerat sapien.</p>
</section>
<section>
<h2>section 2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</section>
</main>
</body>
Proposition de solution pour garder la partie de navigation en haut de page :
body {
margin: 0;
}
nav {
position: -webkit-sticky; /* Safari */
position: sticky;
height: auto;
top: 0;
background-color: #251D3A;
color: #E04D01;
}
main {
overflow: hidden;
background-color: #FF7700;
color: #2A2550;
}
Explications :
Il y a plusieurs valeurs possibles pour la propriété position qui indique la façon dont un élément doit être positionné dans le document. Par défaut, le flux du document se déroule de haut en bas. On peut sortir un élément du flux avec la position absolute par exemple, pour rendre le positionnement de l'élément relatif à son élément parent ou encore la position fixed si on veut le positionner relativement à la fenêtre du navigateur. La valeur sticky quant à elle permet d'aller de la valeur relative (ici, relatif à <body> qui remplit 100% de l'espace) à un positionnement fixe (par exemple : top: 0, soit haut de page) en fonction du défilement du document.
Attention : Internet Explorer ne gère pas le positionnement sticky et Safari a besoin d'un préfixe -webkit.
Elle est complétée par la propriété overflow de l'élément suivant avec une valeur hidden pour que le contenu remplisse tout l'espace disponible avec possibilité de défilement sans barre de défilement.
Il y a peut-être des façons de faire plus propres mais pour l'exemple en question ça fonctionne, en plus d'être très court ce qui est appréciable. On pourra ajouter des marges intérieures (padding) pour que ce soit un peu moins moche, par exemple :
padding: 0 1em;
pour <body> et <main> et
padding: 1em;
pour <nav>.
(si deux valeurs : la première est valable pour haut/bas du bloc, la deuxième pour droite/gauche. Si une seule valeur : valable pour les quatre côtés)
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<meta name="description" content="Une nouvelle page HTML" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Page test</title>
<link rel="stylesheet" href="style.css"/>
<script src="script.js" defer></script>
<base href="https://www.mywebsiteURL.com/" target="_blank">
</head>
<body>
</body>
</html>
Explanations:
<!DOCTYPE html>
so the browser follows the HTML specification
<html lang="fr">
html tag -> to inform the browser it's an HTML document
lang attribute -> to allow screen readers to invoke the correct pronunciation
<head>
head tag -> machine-readable information about the document
<meta>
meta tag -> to add metadata with no specifc tag
charset attribute -> (charset stands for "character set") to specify the document's character encoding (UTF-8 being the universal character set, encodes multiple languages). This tag/attribute must be located within the first 1024 bytes of the document.
name and content attributes (they come together: metadata's name, metadata's value)
-> name value description -> to put in content's value a very short description of the page's content. This will be used by search engines to provide a description of the page.
-> name value viewport (for a browser, 'viewport' means what's visible, a viewport definition tells the browser how to render the page) -> to put in content's value some elements like width that could be device-width and the ratio between the device width and the display zone size (positive number between 0.0 and 10.0), separated by comas. It helps the styling of the page looking similar on mobile as it does on a desktop or laptop and sets the initial zoom level when the page is first loaded by the browser.
<title>
title tag -> to specify the website's title where the HTML document belongs; the title page could also be added (that's what is appearing in the brower's tabs). It's also this title that is indexed by search engines. Note that this is also useful for people using assitive technologies to rapidly aprenhend the website's content.
<link>
link tag -> to link the HTML document to an external resource, for instance a stylesheet or JavaScript
rel attribute -> to specify the relation. Use stylesheet for CSS
href attribute -> stylesheet's URL (can be relative)
<base>
base tag -> specifies a default URL and a default target for all links on a page