Thursday, November 21, 2024
One of my favorite CSS tricks is to use required dynamic HTML attributes as styling hooks. For example, on my Lean Web Club learning platform, you can bookmark your favorite tutorials, tools, and more. The HTML for that is a <button> element that includes the [aria-pressed] attribute. <button aria-pressed="false"> Bookmark This </button>
The [aria-pressed] attribute conveys to screen readers if the <button> is "pressed" and in an active state or not. If the value is true , it's pressed. If it's false , it's not. Let's say I have some default button styles, like this… button { background-color: #f7f7f7; border: 1px solid #e5e5e5; border-radius: 0.25em; color: #272727; padding: 0.25em 1em; }
I'm already toggling the [aria-pressed] attribute value on the <button> whenever it's pressed. let btn = document.querySelector('[aria-pressed]'); btn.addEventListener('click', function () { if (btn.getAttribute('aria-pressed') === 'true') { btn.setAttribute('aria-pressed', false); } else { btn.setAttribute('aria-pressed', true); } });
Rather than also toggling a class, I can use the value of the [aria-pressed] attribute to update the button styles. button { background-color: #f7f7f7; border: 1px solid #e5e5e5; border-radius: 0.25em; color: #272727; padding: 0.25em 1em; } button[aria-pressed="true"] { background-color: #f7272f; border-color: #f7272f; color: #ffffff; }
Now, whenever the state of my <button> changes, its appearance automatically does as well. Here's a demo. Cheers, Chris Want to share this with others or read it later? View it in a browser. |
0 Komentar untuk "[Go Make Things] Attribute styling"