<!--
DEMONSTRATING FOCUS
A quick demonstration of how keyboard focus in HTML.
-->
<h1>Demonstrating focus</h1>
<p>Most interactive HTML elements will accept keyboard focus by default.</p>
<h2>Focusing on elements</h2>
<p>Some of the more common elements that you will use that can have focus:</p>
<ul>
<li><a href="#"><a> elements</a></li>
<li><button><button> elements</button></li>
<li><input type="text" value="<input> fields"></li>
</ul>
<h2>'Making' other elements interactive</h2>
<p>We can make other non-interactive elements - such as images - appear interactive by wrapping them with interactive elements. See the HTML and CSS code for how this <img> element 'appears' interactive</p>
<!--
By wrapping the <img> element in an <a> element we can enable the user to keyboard focus on the <a> which then enables us to style the <img> inside to respond to it. See the CSS for comments on the styling.
-->
<a href="#">
<img src="https://andrewh.ca/teaches/information_design/lectures/04/Sheep.jpg" height="1325" width="2000" alt="A sheep grazing in a field">
</a>
<p class="further-reading">If you would still like to read more on linking files I recommend looking at <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Keyboard">Keyboard Accessibility at MDN</a> and the <a href="https://allyjs.io/data-tables/focusable.html">Focusable elements browser compatibility</a>.</p>
xxxxxxxxxx
/* Have added styling below to the <button>, <a> and <input> elements to ensure they visibly change when they receive keyboard focus */
button:focus, a:focus, input:focus {
background-color: black;
color: white;
}
button:focus {
border: 1px solid white;
}
a:focus {
text-decoration: none;
}
/* <a> elements are inline by default. Switching to display as an inline-block allows it to listen to it's content for its sizing while also having a defineable size. This is important for ensuring the entire image is highlighted when interacting with it using the keyboard. */
a {
display: inline-block;
}
/* The selector below selects any <img> elements that are children of an <a>. This allows us to apply some 'default' styling to <img> elements that are acting as links. */
a img {
transition: opacity 0.35s;
}
/* The selector below allows us to select <a> elements that have keyboard focus, and restyle the <img> elements inside of them accordingly */
a:focus img {
opacity: 0.5;
}
/* Some styling specifically for these additional explanations */
body {
margin: 0 auto;
max-width: 40rem;
font-family: sans-serif;
}
h2 {
margin-top: 4rem;
}
ul {
margin-left: 0;
padding-left: 0;
list-style-type: none;
}
li {
margin-bottom: 1rem;
}
.further-reading {
margin-top: 4rem;
padding-bottom: 2rem;
}
img {
height: auto;
max-width: 100%;
display: block;
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.