Skip to main content
View on YouTube to comment and like!

Syntax Video

Can You Build A Swipe UI With Only CSS?

Chapter 1 00:00

Transcript

This UI is everywhere on mobile, but it absolutely sucks to build, especially with JavaScript, because no matter what you do when you're tracking pan events or you're tracking motion with JavaScript, it never feels as good as the native version. Never. And so I began to think if there was some way I could do this without JavaScript. And let me tell you, I stumbled upon something really cool. Now, I haven't seen anybody else do this yet, but this is a Swiper component made out of pure CSS and HTML, and it can be done in hardly any lines of codes, and it it is unbelievably simple. Now, there's a couple of variations of this that you often see, the swipe until you get to a certain point and then an action is performed, but there's also the version where you pull it open and then it stays open and you can click. Both of these have their unique challenges, and they're both able to be accomplished with CSS in a way that's very flexible.

In fact, you can even throw multiple things in here, like multiple buttons that do whatever you want them to do. The best part about this approach is that it is so minimal and so flexible, you can hook it up to any front-end framework and anything, and you don't have to worry about jank or performance issues. It feels smooth 24/7. Now, I will say I implemented this in my CSS framework graffiti, which is something that I'm just building for fun. And I have a number of different Swiper components if you want to see and feel them in action before getting going. But throughout this video, I'll be giving you a lot of cool tips and tricks as far as how this thing works. But I actually do recommend checking out my library graffiti because there's a lot of fun stuff in here from reels to carousels that use various similar techniques that we're going to be talking about in this video. Okay, so that's enough about my library. Let's go ahead and build our swiper. Before we get going, let me just show you what we have for our base CSS.

This is just a straight up HTML document. I'm not doing this in a framework, but this can be adapted to any framework super easily. I just have a div. I gave an ID of swipe that we're going to be using for JavaScript later and a class of swipe as a more generic thing. And then I threw a button, a div, and then another button. Once we're done with this, you'll be able to throw anything in any of these spots. Like you'll be able to have divs here with multiple buttons. You'll be able to have an H1, an H2, whatever inside of this div. You can fill this thing like anything. And this technique is so flexible, it's just going to work. It's really pretty amazing. And for CSS, I really just don't have too much in here.

I did give this a color scheme light dark, some variables, a light dark background swap, so that way we're not staring at a bright white screen the whole time. And I did give a box sizing border box, which you will need. So this is included in most CSS resets, but we do need it for this. Other than that, a more CSS reset stuff, I gave a margin to the body. I gave it a body, background color, and a color, as well as a font size of 36 pixels. You can just copy and paste this code directly from the starter just in the video description if you'd like or you can type it all in yourself too if that's what you like.

This is what it looks like by default. Right, we have no even default font set in here. So, let's go ahead and get this going. So, what we want to do is we want to target the swipe div first and foremost and we're going to build off of there. Again, the the key thing here is that we have the wrapper and then three children items. whatever the first container is, the main swipe section, and then the last container, whether that is just a button or a div full of buttons. So, let's head to our CSS and let's target that swipe div. We want to say swipe. So, inside of this swipe, what we're going to want to do is first give this a display of grid. So, we're going to say display grid. The grid template columns that we're going to use are grid template columns. And we're going to want to give these a columns of auto, one fr, and then auto. This means that the first item and the last item take up just as much space as they need to, and the 1 FR will fill the remaining space. Okay, the next thing we want to

do is give this an overflow X of auto so that way it scrolls. We're going to be using scrolling to accomplish this. That's going to be one of the reasons why it's so fast. The browser scrolls really well. And then we're going to give this a border block to define a border for the top and bottom of this. A simple border block of 1 pixels. And we can pick any random gray number out of the hat. 666 sounds good. Solid.

And then just like that. Okay. That way we at least have some top and bottom defined borders when we have these. Um you could This part's unnecessary, but it's nice to have for the demo. Okay. So the next thing we want to do is target the second child. The second child is going to be this main div section right here. Okay. And because it's always going to be three children in here. And so to target the second child, we're going to say give me the immediate colon nth child.

And then the nth child is going to be the second child. The second child is going to be that middle div like I mentioned. and we're going to give it a width of 100 VW for now. This is going to make it fill up the entire vertical width. At this point, you could give the buttons all kinds of styles. I'm going to in this particular example because I want the button styles to not be tied to the swiper itself. I'm just going to give them some inline style right now.

If you're like a Tailwind user or something, you throw a bunch of Tailwind on here. Who knows? Or you could use whatever CSS you like. Uh CSS is free. So you can say background is going to be equal to something like red and the width is going to be equal to something like 200 pixels like that. And then that makes this a little bit bigger and wider like we had in our demo. Of course, you can't really see that X checkbox anymore. And this is going to be the same problem with the green one. You you could always make these different colors, but for the sake of this demo, who cares, right? Okay, so we have these both in here. And what you see now is we have a scrolling section like this. And that looks pretty neat. Now, another thing I want to do on here is add some padding to this middle child. So, the padding is going to be something like 10 pixels. Uh, we'll just do 10 pixels all around. Right. Actually, I take that back. We'll do 20 pixels on the block dimension. Just like that. And that gives us a little bit more space here.

But we're not any closer to having a swiper. That is until we bring in scroll snap. Now, scroll snap is an incredible API, but typically when you see scroll snap being done, the snap is applied to every single children. Uh, we're actually going to take a different approach than snapping to the start or the end of every children, and I'll show you that in just a second. So, what we want to do is on the swipe section, we're going to use scroll hyphen snap type is the thing that we want. Scroll snap type. And we're going to say it snaps on the X dimension. and it's going to be mandatory. We don't want any any iffiness. We want it to always snap. [snorts] Now, the next thing here that we'll want is we'll want to tell the nth child, as in only the second child, just the second child, scroll, snap, align. Okay. And your options are

start, end, center. Uh we're going to say center for this one. I save this and check it out. We have a swiper. Now, the cool thing is is because we've only assigned this scroll snap a line, it's always going to snap back to the center. This is the same functionality you see in a ton of these swiper interfaces. In fact, the one on Reddit that I showed uh is like you swipe it, it triggers an event, it triggers an upvote. At the end of this video, I'll show you some really simple JavaScript that you can fire off an event or you can do it in your framework of choice. But just look at that. That's it. When I was said this was simple, I bet you didn't know it was this simple. This is very simple. Now, the challenge then becomes the leaving it open style. Now, the style that stays open, believe it or not, as you will see, is much more challenging because when I first did this technique, I'm like, I figured it out. This is incredible. I got it. Now, let me just

do the next one, which stays open. Oh, shoot. Uh, now I have to bring in JavaScript to set the initial index because scroll snap does not allow you to change the initial index, at least not yet in all major browsers. And you can fix that with JavaScript relatively easy, but I took it upon myself to challenge myself to see if I could do it with just CSS. And the results are incredible. So, check this out. What we're going to want to do is we're going to want to create a duplicate of this. I am going to remove the idea of swipe because we're going to be using that for JavaScript later on. I'm going to add a second class of hold here. Okay, with this class of hold, we're going to be able to key off of that, keep most of our styles from the prior swipe one, and we're going to be able to add some additional things. So, with hold, what we can do is we can say amperand hold. So, if the swipe has an additional class of hold, what do we want to do?

Well, we want to target all children of this. So, all children. And we're going to want to say the colon first child as well as we'll want to target also the colon last child because the first child needs a scroll snap align of start and the last child will need a scroll snap align of end. And that makes sense because you want the snap to start on the start of the one, the middle of the middle one, and the end of the one on the end. So if I refresh my page, you can see we now have a red zone here. We have the main zone. And if I pull it here, it stays here. And if I pull it here, it stays here. And if I pull it here, it stays here. So it holds open.

But again, there's no way to set the starting index. So there's no way for me to say, "Hey, start here." and then that would just cause it to just work. [snorts] And so again, I went to JavaScript and I fixed this with JavaScript first, but let me tell you, there is an incredible hack that was given to me by Adam Argyle. Now, I didn't tell him what I was building. I just asked about starting on a specific index, and he said, well, you could do this, and let me tell you, it worked first try. So, what we're going to be doing is we're going to create an animation. Believe it or not, we're going to use key frames. And the key frames is just going to be named scroll hold. Now, you might not know this. Uh nice little tidbit here. When you're doing key frame animations, you don't need to specify the from and to uh positions or 0 to 100% in animations. Uh from and two is just a shorthand for 0 to 100. If you're doing 0 to 100, it's always going to go from its from value to its to value. believe it that uh and

and that means if we were to do something like two opacity zero, this would actually animate from one to zero uh without you having to specify that it initially starts at one. So neat little tidbit there about animations. Now the animation that we're going to be doing is really interesting because all we're going to be doing is setting scroll snap align to start like this. And you might thinking I can't animate that. No, you can't. But you can use an animation to set this immediately after load. So fast that you won't even see it. So we'll say animation and we can say scroll hold and it's going to happen in 0.0.001s.

I haven't tried smaller values. This just worked fine. So I kept it. And then we're going to say the last property is forwards. Now, forward simply just means that after the animation is complete, it's just going to stay there and it's not going to reset itself or go backwards. And so, what this is doing is after this first 0.001 second, what it's going to do is it's going to apply scroll snap align. So, when the page first loads, it only sees scroll snap align center on the nth child and it immediately snaps to that.

And because there's nothing else swiping that thing, it's not going to move it again after it applies the scroll snap align from this animation. We refresh this and you can instantly see you pull this open, it stays open. You pull this open, it stays open. And just like that, you can swipe between the two just like normal. And man, this feels so smooth.

Especially on mobile, this feels as native as it can get. Now, the coolest thing about this technique and about any of this stuff besides the minimal amount of things is that since we're using first child, last child, and nth child, too, the children can be all kinds of things. Uh they could contain all sorts of stuff, images, whatever, divs, and it's just going to work. And it's so flexible. Now, one last thing to enhance this because this works great on something that's like full page. Now, 99% of the time, these things are going to be full page, right? they're going to take up the entire page. But what if what if they're not? And then therefore this would break. Why would this break?

Well, it would break because we are using 100% of the viewport width for this thing. You might not always want 100% of the viewport width. Sometimes you might want just the width of its container. Incoming container queries. Now container queries solve this in just two lines of code. What we can do is we can say container hyphen type and the type is going to be set to inline size. Okay, so the container is now inline size. And because we have an inline size container, instead of 100vw for the width of this thing, we can say it's 100 container query width like so. And notice how our demos didn't change at all. They didn't change at all. But now what we could do is theoretically let's put one of these and let's put it inside of a div and let's give this div some style and this is just going to be a width

of 50%. I I think that's going to look terrible, but here it is. Now this swiper works the exact same just inside of this minimally sized div. The 50%'s a little rough uh considering how much space is inside of this thing, but look at that. It just works. And that's really great because the container query takes care of all the tough stuff. Now, you might see, especially on Windows computers, the scroll bar. Now, this is not a UI that plays well on desktop.

I'll tell you that right now. And for desktop, you're probably not going to want to have this be the UI, but again, the DOM structure of this thing allows that your CSS can be changed and have this just be for mobile, no problem. Or if you're building mobile apps, then you don't need to worry about it. So, with that in mind, I think we can safely remove these scroll bars because typically you don't want to see these things and you don't really see them.

So, let's go ahead and remove them by saying scroll bar width is going to be equal to none. And now, at least on Mac OS, you won't see them here like this. Now, some people won't like that, but again, this is largely a mobile UI anyways, and probably not something you're going to give your users on your desktop computer. Now, I did promise you we would write some JavaScript to give this some events before I go. Let's go ahead and do that in our index.html.

This is going to be some really simple barebones JavaScript, but it will just illustrate a little bit of how you might approach this if you haven't done this type of thing before. Now, we're only going to do it on the top one, but we're going to say const swiper is equal to document.getelement by ID. And then we're going to say the ID is swipe, I believe. Swipe. I should I should uh standardize on swipe or swiper. I haven't [snorts] done that apparently. Now, we have the swiper.

Now, what we're going to want to do with the swiper is give it an event listener. So, swiper.adde eventlister. Uh, I'm flying blind without Typescript here. This is a lot of fun. I I love my autocomplete, right? And the event is going to be scroll. And the function that we're just going to run is on scroll. Okay. I'm not worrying about naming things or name spacing right now or anything like that. Uh, so there we go. On scroll is not defined. We can give it a function on scroll. This function has access to the event. From the event, we can get access to the current target. So, const scroll div is equal to e.curren target. We'll also want to grab the center of the scroll div. So, we'll say scroll div. Oh, we'll just say scroll center. We don't need to say scroll div center is going to be equal to scroll div uh scroll width divided by two like so. And then

we're going to want to grab the viewport center which is really just the scroll div.client width. So scroll uh const. So viewport center is equal to scroll div.client client width divided by two like that. And then we're going to want to go ahead and grab the current distance traveled or the current position of it, not the current distance. And to get that, you grab the scroll div. So, we'll just say current uh cut current is equal to the scroll div and uh we're going to grab the scroll left plus and then we're just going to grab the viewport center.

If you wanted to see this in action to make sure that we're on the right track here, in fact, that's always good to do. I'm going to console.log Oh my god. Uh my current here. And now when I swipe it and let me bump up this so you can see it. Now when I swipe it, you can see that the current position is output here. And if I go backwards, it goes backwards. So that means that this is the distance traveled. So if we want to capture what's called the delta or the delta in the x direction or the distance changed, what we want to do is say const dx or the delta in the x direction is going to be equal to the current minus the scroll center. So how much it's moved from the center. We can log out the dx now. And this should give us a value between 200 if we go far to the left or right and 200 negative 200 far to the left. And uh therefore we can be able to then fire off events on this

thing which is really great because that's all we need to do is to be able to respond to this. Now again you can do this in all sorts of way. I have a spelt kit version of this that I run that uses an attachment that just fires off and it will return the dx. It will return the percentage that it's gone like as say it's gone 100 percentage. um and then it will fire off a function that you may have passed into it. But again, this is just basic straight up JavaScript. And now you don't have to worry about changing the position values with JavaScript, which can be heavy. You got to use request animation frame. You got to use motion libraries. It can be heavy. We can use the browser to do that part. And all we're using JavaScript for is just to spy on it and say, "Hey, did that value get to what we needed to get?" Okay, now that it has, we can do all sorts of stuff. We can fire off an event. We can even remove this from the DOM. We can do an upvote. We can hit an API. We can uh optimistically update

something. And that's it. This is it. And that would be it. But there's just one more issue. Safari. Safari does not like the key frame issue. So that means we do need to have a small bit of JavaScript to get our scroll in the initial position at the start. But that doesn't mean we're totally screwed here because we're going to maintain the ability to use the swipe, which is what feels so good using scroll snap and CSS, but we do need to set the initial scroll position on Safari, which is a tremendous bummer and something I hope gets fixed soon in Safari because when the scroll snap is reapplied via the animation, it actually snaps back to the front again. But this is actually a super easy fix within JavaScript. So let's get that done. So you can do this in your framework of choice. I wrote a spelt attachment to do this that will be

in the graffiti source code if you want to see that. However, if you just want to do this the quick and dirty way, we just need to do const and we'll say holds as in all of the holds or whatever you may call this. We're going to use a document query selector all. So we're going to use query selector all and we're going to grab all of them that have the hold class. So all of them that have the hold class, we're then going to loop over using a for each. So we're going to say holds for each and we're going to have the hold parent because this is the wrapper of the thing. And we're going to want to grab the center div. Now the center div for each of these is available to be gotten with we'll just call this a hold is equal to the hold parent dot children and since again we always know there's going to be three children it is going to be the second one zerobased indexing we want a number one here and then so

that way this renders in a time that makes sense we'll do request animation frame and we'll just have a simple arrow function in here that looks like this And from here we'll set the hold_parent.croll leftft is going to be equal to the hold.offset left. So basically the scroll position of the entire thing is going to be set to the left position of the center div.

Now one thing you'll notice is is that this will work fairly reliably but once every few refreshes the timing won't add up. And there's a couple of ways to fix that. One of which would be to use a set timeout instead of request animation frame. But if you want it to be reliable every time, you can actually get rid of this incredible key frame trick that we did. But this will work in most browsers. And hopefully uh this is something that does get wrapped up in Safari. If we set this back to scroll, snap align start. And now refresh it, you're going to be able to see that this will work super reliably every time. The swiper then functions exactly as you'd expect. So, even though we're needing to be bailed out just ever so slightly with JavaScript, the scroll performance on this thing can't be

Quote it with credit and a link. Quoting Syntax