M. Andrew Darts
Posted on December 3, 2019
Modals are everywhere
Modals are a staple in all web apps and sites. How many times have you pulled for a Javascript library for modals. Or worse, implemented your own. Probably every project you have ever done. I have recently taken the approach of only using Javascript when completely necessary. This has pushed me to explore CSS in a new way. If you need a modal in your web project it is 100% achievable with just CSS. Let's see how!
Target Pseudo Selector
You may be familiar with pseudo selectors like :before
, :after
, :checked
, & :nth-child(n)
. These are super useful for every day use. There is one pseudo selector you may not be aware of. The way :target
works is if the location hash matches an element it will trigger the :target
pseudo selector on that element. For instance, if my url is mysite.com#article
the element with the id #article
will trigger the :target
pseudo selector. This may seem very simple, because it is! Let your imagination go with it. There are many things you can build with this knowledge, with no Javascript.
Pro Tip
This :target
pseudo selector supports CSS animations and transitions.
This means you can easily animate between states, this gives you quite a bit of power!
Below is an example of an animating modal with just CSS.
Posted on December 3, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.