Tag: States

Fun Times Styling Checkbox States

We might leave a text input unstyled. We might leave a link unstyled. Even a button. But checkboxes… we don’t leave them alone. That’s why styling checkboxes never gets old.

Although designing checkboxes is not that complicated, we also don’t have to settle for simple background color changes, or adding and removing borders, to indicate state changes. We also don’t have to pull out any fancy design skills — that we don’t possess — to make this work. I’ll show you how.

Basics

In the following demos, the checkboxes pretty much have the same three-stack layout — at the bottom is a checkbox, and on top of it are two stacked elements, or pseudo-elements. The checkbox is indicated as checked or unchecked depending on which of the two is visible.

If you look at the CSS code in the pens you’ll notice all the layouts — including the one for the checkboxes — are grids. You can use other layouts that feel right for your use case (and learn more in the CSS-Tricks Grid Guide). Additional notes on code and design alternatives are at the end of the source code inside the pens.

In addition, any elements stacked on top of the checkbox have pointer-events: none so they don’t prevent users from clicking or tapping the checkbox.

Let’s now get to the first method.

Idea 1: Blended backgrounds as a state

Blending in CSS is a versatile technique. Manipulating colors relative to two or more elements or backgrounds can be handy in contexts you might not have thought of.

One such instance is the checkbox.

<input id="un" type="checkbox"> <label for="un">un</label> <!-- more checkboxes --> 
input[type=checkbox]::before, input[type=checkbox]::after {   mix-blend-mode: hard-light;   pointer-events: none;   /* more style */ } input[type=checkbox]::before {   background: green;   content: '✓';   color: white;   /* more style */ } input[type=checkbox]::after {   background: blue;   content: '⨯';   /* more style */ } input[type=checkbox]:checked::after {   mix-blend-mode: unset;   color: transparent; }

In this demo, I’ve styled the checkbox’s pseudo-elements green and blue, stacked them up, and gave them each a mix-blend-mode value. This means the background of each element blends with its backdrop.

I used the hard-light value, which emulates the result of either multiply or screen depending on if the top color is darker or lighter. You can learn in depth about different blend modes over at MDN.

When the box is checked, the ::after pseudo-element’s mix blend mode value is unset, resulting in a different visual.

Idea 2: Make a 3D animation

Animating a block of color is fun. Make them seem 3D and it’s even better. CSS has the means to render elements along an emulated 3D space. So using that, we make a 3D box and rotate it to indicate the checkbox state change.

<div class="c-checkbox">   <input type="checkbox" id="un">   <!-- cube design -->   <div><i></i><i></i><i></i><i></i></div> </div> <label for="un">un</label> <!-- more checkboxes -->
.c-checkbox > div {   transition: transform .6s cubic-bezier(.8, .5, .2, 1.4);   transform-style: preserve-3d;   pointer-events: none;   /* more style */ } /* front face */ .c-checkbox > div > i:first-child {   background: #ddd;   transform:  translateZ( -10px ); } /* back face */ .c-checkbox > div > i:last-child {   background: blue;   transform:  translateZ( 10px ); } /* side faces */ .c-checkbox > div > i:nth-of-type(2), .c-checkbox > div > i:nth-of-type(3) {   transform: rotateX(90deg)rotateY(90deg);   position: relative;   height: 20px;   top: 10px; } .c-checkbox > div > i:nth-of-type(2) {   background: navy;   right: 20px; } .c-checkbox > div > i:nth-of-type(3) {   background: darkslategray;   left: 20px; }

The <div> after the checkbox becomes a container of a 3D space — its child elements can be placed along the x, y and z axes — after it’s given transform-style: preserve-3d;.

Using the transform property, we place two <i> elements (grey and blue colored) with some distance between them across the z-axis. Two more are wedged between them, covering their left and right sides. It’s like a cardboard box that’s covered except at the top and bottom.

When the checkbox is checked, this grey and blue box is rotated sideways to face the other side. Since I’ve already added a transition to the <div>, its rotation is animated.

input:checked + div {    transform: rotateY( 180deg );  }

Idea 3: Playing with border radius

Changing a checked box’s border radius? Not that fun. Changing also the border radius of other boxes near it? Now we have something.

<input type="checkbox" id="un"> <label for="un">un</label> <!-- more rows of checkboxes -->
input {   background: #ddd;   border-radius: 20px;   /* more style */ } input:not(:first-of-type)::before {   content: '';       transform: translateY(-60px); /* move up a row */   pointer-events: none; } input:checked + * + input::before, input:last-of-type:checked {   border-radius: 20px;   background: blue; } input:checked + * + input:checked + * + input::before {   border-top-left-radius: unset !important;   border-top-right-radius: unset !important; } input:checked::before {   border-bottom-left-radius: unset !important;   border-bottom-right-radius: unset !important; } /* between the second-last and last boxes */  input:nth-of-type(4):checked + * + input:checked {   border-top-left-radius: unset;   border-top-right-radius: unset; }

If you’d just interacted with the demo before, you’ll notice that when you click or tap a checkbox, it not only can change its own borders but also the borders of the boxes after and before it.

Now, we don’t have selectors that can select elements prior, only the ones after. So what we did to control the appearance of a preceding box is use the pseudo-element of a checkbox to style the box before it. With exception of the first box, every other box gets a pseudo-element that’s moved to the top of the box before it.

Let’s say boxes A, B and C are one after another. If I click B, I can change the appearance of A by styling B’s pseudo-element, B by styling C’s pseudo-element, and C by styling D’s pseudo-element.

From B, the pseudo-elements of B, C and D are accessible — as long as the next element selector can be used between them in the layout.

The four corners of each checkbox are initially rounded when checked and unchecked. But if a box is checked, the following box’s top corners and preceding box’s bottom corners are straightened (by overriding and removing their border radii).

Idea 4: Using a CSS mask

Toggles, switches… they are also checkboxes as far as the code goes. So we can style the boxes as toggles for this one, and it’s done with a CSS mask, which Chris has written about before. But in a nutshell, it’s a technique where we use an image to filter out portions of its backdrop.

<input type="checkbox"> <div class="skin one"></div> <div class="skin two"></div>
.one.skin {   background: no-repeat center -40px url('photo-1584107662774-8d575e8f3550?w=350&q=100'); } .two.skin {   background: no-repeat center -110px url('photo-1531430550463-9658d67c492d?w=350&q=100');   --mask: radial-gradient(circle at 45px 45px , rgba(0,0,0,0) 40px, rgba(0,0,0,1) 40px);   mask-image: var(--mask); -webkit-mask-image: var(--mask); }

Two skins (displaying landscape photos) are on top of a checkbox. The topmost one gets a mask-image that’s in the shape of a typical toggle switch — a transparent circle at the left, and the rest is a fully opaque color. Through the transparent circle we see the photo below while the rest of the mask image shows the photo at the top.

When a checkbox is clicked, the transparent circle is moved to the right, so we see the image at the top through the circle while the rest shows the photo at the bottom.

input:checked ~ .two.skin {   --mask: radial-gradient(circle at 305px 45px, rgba(0,0,0,1) 40px, rgba(0,0,0,0) 40px);   mask-image: var(--mask); -webkit-mask-image: var(--mask); }

Idea 5: Using box shadow

Let’s end with the simplest — but what I consider to be the most effective — method of them all: an animated inset box-shadow.

<input id="un" type="checkbox"> <label for="un">un</label>
input {   transition: box-shadow .3s;   background: lightgrey;   /* more style */ } input:checked {    box-shadow: inset 0 0 0 20px blue; }

There are some CSS properties that can be animated by default and one of them is box-shadow. This type of subtle animation goes well with a minimalist theme.


That’s it! I hope this sparks some inspiration the next time you find yourself working with checkboxes. CSS gives us so many possibilities to indicate state changes, so have a little fun and please share if you have any interesting ideas.


The post Fun Times Styling Checkbox States appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , ,

The Nine States of Design

Here’s a really good ol’ post from way back in 2015 all about the nine states of design and how we should think all the edge cases whenever we’re building interfaces. Vince Speelman writes:

Modern UI teams are designing components first; Interfaces are merely the thoughtful composition of components. This leaves an often glaring hole for users on “the unhappy path” — The places where users may, intentionally or not, stray from your idealized flow. As we learn to craft systems rather than pages, we must invest effort into shaping these often missed states of design and create with a component lifecycle that can support everyone. Here’s the lifecycle as I see it:

  1. Nothing state
  2. Loading
  3. None
  4. One
  5. Some
  6. Too many
  7. Incorrect
  8. Correct
  9. Done

During the design process I think everyone (including me!) tends to focus on the ideal state of a component or interface, often leaving the extremely important edge cases forgotten until the last moment. I think I need to stick this list to my screen so I don’t forget it in my next project.

Direct Link to ArticlePermalink


The post The Nine States of Design appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, ,
[Top]

Dealing With Stale Props and States in React’s Functional Components

There’s one aspect of JavaScript that always has me pulling my hair: closures. I work with React a lot, and the overlap there is that they can sometimes be the cause of stale props and state. We’ll get into exactly what that means, but the trouble is that the data we use to build our UI can be totally wrong in unexpected ways, which is, you know, bad.

Stale props and states

Long story short: it’s when code that is executed asynchronously has a reference to a prop or state that is no longer fresh, and thus, the value it returns is not the latest one.

To be even more clear, let’s play around with the same stale reference example React has in its documentation.

function Counter() {   const [count, setCount] = useState(0);    function handleAlertClick() {     setTimeout(() => {       alert("You clicked on: " + count);     }, 3000);   }    return (     <div>       <p>You clicked {count} times</p>       <button onClick={() => setCount(count + 1)}>Click me</button>       <button onClick={handleAlertClick}>Show alert</button>     </div>   ); }

(Live demo)

Nothing fancy here. We have a functional component named Counter. It keeps track of how many times the user has clicked one button and shows an alert that displays how many times that button was clicked when clicking another button. Try this:

  1. Click the “Click me” button. You are going to see the click counter go up.
  2. Now click the “Show alert”button. Three seconds should go by and then trigger an alert telling you how many times you clicked the “Click me” button.
  3. Now, click the “Show alert” button again and quickly click the “Click me” button before it triggers the alert in three seconds.

See what happens? The count shown on the page and the count shown in the alert do not match. The number in the alert is not just some random number, though. That number is the value the count variable had in the moment the asynchronous function inside the setTimeout was defined, which is the moment the “Show alert” button is clicked.

That’s just how closures work. We’re not going to get into the specifics of them in this post, but here are some docs that cover them in greater detail.

Let’s focus on how we can avoid these stale references with our states and props.

React offers a tip on how to deal with stale dates and props in the same documentation where the example was pulled.

If you intentionally want to read the latest state from some asynchronous callback, you could keep it in a ref, mutate it, and read from it.

By keeping the value  asynchronously in a ref, we can bypass stale references. If you need to know more about ref in functional components, React’s documentation has a lot more information.

So, that begs the question: How can we keep our props or state in a ref?

Let’s do it the dirty way first.

The dirty way to store props and state in a ref

We can easily create a ref using useRef() and use count as its initial value. Then, wherever the state is being updated, we set the ref.current property to the new value. Lastly, use ref.current instead of count in the asynchronous part of our code.

function Counter() {   const [count, setCount] = useState(0);   const ref = useRef(count); // Make a ref and give it the count    function handleAlertClick() {     setTimeout(() => {       alert("You clicked on: " + ref.current); // Use ref instead of count     }, 3000);   }    return (     <div>       <p>You clicked {count} times</p>       <button         onClick={() => {           setCount(count + 1);           ref.current = count + 1; // Update ref whenever the count changes         }}       >         Click me       </button>       <button         onClick={() => {           handleAlertClick();         }}       >         Show alert       </button>     </div>   ); }

(Live demo)

Go ahead and do the same as last time. Click “Show alert” and then click “Click me” before the alert is triggered in three seconds.

Now we have the latest value!

Here’s why it works. When the asynchronous callback function is defined inside setTimeout, it saves a reference to the variables it uses, which is count in this case. This way, when the state updates, React not only changes the value but the variable reference in memory is completely different as well.

This means that — even if the state’s value is non-primitive — the variable you are working with in your asynchronous callback is not the same in memory. An object that would typically keep its reference throughout different functions now has a different value.

How does using a ref solve this? If we take a quick look at React’s docs again, we find an interesting, but easy-to-miss, bit of information:

[…] useRef will give you the same ref object on every render.

It doesn’t matter what we do. Throughout the lifetime of your component, React will give us the exact same ref object in memory. Any callback, no matter when it’s defined or executed, is working with the same object. No more stale reference.

The cleaner way to store props and state in a ref

Let’s be honest… using a ref like that is an ugly fix. What happens if your state is being updated in a thousand different places? Now you have to change your code and manually update the ref in all those places. That’s a no-no.

We are going to make this more scalable by giving ref the value of the state automatically when the state changes.

Let’s start by getting rid of the manual change to the ref in the “Click me”button.

Next, we make a function called updateState that is called whenever we need to change the state. This function takes the new state as an argument and it sets the ref.current property to the new state and updates the state as well with that same value.

Finally, let’s substitute the original setCount function React gives us with the new updateState function where the state is being updated.

function Counter() {   const [count, setCount] = useState(0);   const ref = useRef(count);    // Keeps the state and ref equal   function updateState(newState) {     ref.current = newState;     setCount(newState);   }    function handleAlertClick() { ... }    return (     <div>       <p>You clicked {count} times</p>       <button         onClick={() => {           // Use the created function instead of the manual update           updateState(count + 1);         }}       >         Click me       </button>       <button onClick={handleAlertClick}>Show alert</button>     </div>   ); }

(Live demo)

Using a custom hook

The cleaner solution works just fine. It gets the job done just like the dirty solution, but only calls a single function to update the state and ref.

But guess what? We can do better. What if we need to add more states? What if we want to do this in other components too? Let’s take the state, ref and updateState function and make them truly portable. Custom hooks to the rescue!

Outside the Counter component, we are going to define a new function. Let’s name it useAsyncReference. (It can be named anything, really, but note that it’s common practice to name custom hooks with “use” as a prefix.) Our new hook will have a single parameter for now. We’ll call it value.

Our previous solution had the same information stored twice: once in the state and once in the ref. We are going to optimize that by keeping the value just in ref this time. In other words, we will create a ref and give it the value parameter as its initial value.

Right after the ref, we will make an updateState function that takes the new state and sets it to the ref.current property.

Lastly, we return an array with ref and the updateState function, very similar to what React does with useState.

function useAsyncReference(value) {   const ref = useRef(value);    function updateState(newState) {     ref.current = newState;   }    return [ref, updateState]; }  function Counter() { ... }

We are forgetting something! If we check the useRef documentation, we learn that updating a ref does not trigger a re-render. So, while ref has the updated value, we wouldn’t see the changes on screen. We need to force a re-render every time ref gets updated.

What we need is a fake state. The value doesn’t matter. It’s only going to be there to provoke the re-render. We can even ignore the state and only keep its update function. We are calling that update function forceRender and giving it an initial value of false.

Now, inside updateState, we force the re-render by calling forceRender and passing it a state different to the current one after setting ref.current to newState.

function useAsyncReference(value) {   const ref = useRef(value);   const [, forceRender] = useState(false);    function updateState(newState) {     ref.current = newState;     forceRender(s => !s);   }    return [ref, updateState]; }  function Counter() { ... }

Take whatever value it has and return the opposite. The state doesn’t really matter. We are merely changing it so React detects a change in state and re-renders the component.

Next, we can clean the Count component and remove the previously used useState, ref and updateState function, then implement the new hook. The first value of the returned array is the state in the form of a ref. We’ll keep calling it count, where the second value is the function to update the state/ref. We’ll continue calling it setCount.

We also have to change the references to the count since now that they all must be count.current. And we must call setCount instead of calling updateState.

function useAsyncReference(value) { ... }  function Counter() {   const [count, setCount] = useAsyncReference(0);    function handleAlertClick() {     setTimeout(() => {       alert("You clicked on: " + count.current);     }, 3000);   }    return (     <div>       <p>You clicked {count.current} times</p>       <button         onClick={() => {           setCount(count.current + 1);         }}       >         Click me       </button>       <button onClick={handleAlertClick}>Show alert</button>     </div>   ); }

Making this work with props

We have a truly portable solution for our problem. But guess what… there’s still a little more to do. Specifically, we need to make the solution compatible with props.

Let’s take the “Show alert” button and handleAlertClick function to a new component outside the Counter component. We are gonna call it Alert and it’s going to take a single prop called count. This new component is going to show the count prop value we are passing it in an alert after a three second delay.

function useAsyncReference(value) { ... }  function Alert({ count }) {   function handleAlertClick() {     setTimeout(() => {       alert("You clicked on: " + count);     }, 3000);   }    return <button onClick={handleAlertClick}>Show alert</button>; }  function Counter() { ... }

In Counter, we’re swapping the “Show alert” button for the Alert component. We’ll pass count.current to the count prop.

function useAsyncReference(value) { ... }  function Alert({ count }) { ... }  function Counter() {   const [count, setCount] = useAsyncReference(0);    return (     <div>       <p>You clicked {count.current} times</p>       <button         onClick={() => {           setCount(count.current + 1);         }}       >         Click me       </button>       <Alert count={count.current} />     </div>   ); }

(Live demo)

Alright, time to run through the testing steps again. See? Even though we are using a safe reference to the count in Counter, the reference to the count prop in the Alert component is not asynchronously safe and our custom hook is not suitable to use with props… yet.

Lucky for us, the solution is fairly simple.

All we have to do is add a second parameter to our useAsyncReference hook named isProp, with false as the initial value. Just before we return the array with ref and updateState, we set up a condition. If isProp is true, we set the ref.current property to value and only return ref.

function useAsyncReference(value, isProp = false) {   const ref = useRef(value);   const [, forceRender] = useState(false);    function updateState(newState) {     ref.current = newState;     forceRender(s => !s);   }    if (isProp) {     ref.current = value;     return ref;   }    return [ref, updateState]; }  function Alert({ count }) { ... }  function Counter() { ... }

Now let’s update Alert so that is uses the hook. Remember to pass true as a second argument to useAsyncReference since we are passing a prop and not a state.

function useAsyncReference(value) { ... }  function Alert({ count }) {   const asyncCount = useAsyncReference(count, true);    function handleAlertClick() {     setTimeout(() => {       alert("You clicked on: " + asyncCount.current);     }, 3000);   }    return <button onClick={handleAlertClick}>Show alert</button>; }  function Counter() { ... }

(Live demo)

Give it another try. Now it works perfectly whether you use states or props.

One last thing…

There’s one last change I’d like to make. React’s useState docs tell us that React will bail out of a re-render if the new state is identical to the previous one. Our solution doesn’t do that. If we pass the current state again to the hook’s updateState function, we will force a re-render no matter what. Let’s change that.

Let’s put the body of updateState inside an if statement and execute it when ref.current is different than the new state. The comparison must be done with Object.is(), just like React does.

function useAsyncReference(value, isProp = false) {   const ref = useRef(value);   const [, forceRender] = useState(false);    function updateState(newState) {     if (!Object.is(ref.current, newState)) {       ref.current = newState;       forceRender(s => !s);     }   }    if (isProp) {     ref.current = value;     return ref;   }    return [ref, updateState]; }  function Alert({ count }) { ... }  function Counter() { ... }

Now we are finally done!


React can sometimes seem like a black box that is full of little quirks. Those quirks might be daunting to deal with, like the one we just tackled. But if you are patient and enjoy being challenged, you’ll soon realize it’s an awesome framework and a pleasure to work with.

The post Dealing With Stale Props and States in React’s Functional Components appeared first on CSS-Tricks.

CSS-Tricks

, , , , , ,
[Top]

Solving Sticky Hover States with @media (hover: hover)

Mezo Istvan does a good job of covering the problem and a solution to it in a blog post on Medium¹.

If you tap on something that has a :hover state but you don’t leave the page then, on a mobile device, there is a chance that :hover state “sticks.” You’ll see this with stuff like jump-links used as tabs or buttons that trigger on-page functionality.

button:hover {   border: 3px solid green; /* might stick! */ }

The solution, or trick, is a new(ish) “CSS4” media query that allows you only to apply styles on devices with hover capability.

@media (hover: hover) {   button:hover {     border: 3px solid green; /* solves sticky problem */   } }

Your typical touch screen mobile device will fail that media query, the style won’t apply, and you’ll avoid the sticky problem.

Support is solid, so not much worry there.

  1. It almost feels like we have to apologize to linking to things on Medium lately. I have no idea what you’re going to experience when you get there. Will you just be able to read it? Will it be a teaser where you have to log in to read more? Will it be behind a paywall? I have no idea. In this case, hopefully, this link post has enough info in it that isn’t not blocking you from learning anything.

Direct Link to ArticlePermalink

The post Solving Sticky Hover States with @media (hover: hover) appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]

Sticky Table of Contents with Scrolling Active States

Say you have a two-column layout: a main column with content. Say it has a lot of content, with sections that requires scrolling. And let’s toss in a sidebar column that is largely empty, such that you can safely put a position: sticky; table of contents over there for all that content in the main column. A fairly common pattern for documentation.

Bramus Van Damme has a nice tutorial on all this, starting from semantic markup, implementing most of the functionality with HTML and CSS, and then doing the last bit of active nav enhancement with JavaScript.

For example, if you don’t click yourself down to a section (where you might be able to get away with :target styling for active navigation), JavaScript is necessary to tell where you are scrolled to an highlight the active navigation. That active bit is handled nicely with IntersectionObserver, which is, like, the perfect API for this.

Here’s that result:

It reminds me of a very similar demo from Hakim El Hattab he called Progress Nav. The design pattern is exactly the same, but Hakim’s version has this ultra fancy SVG path that draws itself along the way, indenting for sub nav. I’ll embed a video here:

That one doesn’t use IntersectionObserver, so if you want to hack on this, combine ’em!

The post Sticky Table of Contents with Scrolling Active States appeared first on CSS-Tricks.

CSS-Tricks

, , , , ,
[Top]