Ahmad Usman
Ahmad Usman

Ahmad Usman

Is Javascript the only option to toggle modals?

Ahmad Usman's photo
Ahmad Usman
ยทNov 14, 2020ยท

2 min read

That's the question that has always been on my mind untill I stumbled upon a tutorial explaining another method of achieving this using pure CSS.

It is made possible in pure CSS using the :target pseudo-selector. The pseudo selector is available on any element with an id matching the URL fragment.

What's a URL fragment?๐Ÿค”

URL fragment is the part of any URL after the # as in "cssmodal.com/index.html#modal", here the #modal is the URL fragment thus an element with an id of modal will have a :target pseudo-selector.

We can simply use an < a > element with it's link pointing to a part of the page (the modal).

<a href="#modal">Open modal </a> <!--Clicking this link will add the "#modal" fragment to the URL --> 

<div id="modal"></div> <!-- this div will be the target it's id matches the URL fragment -->

So how can we use the :target pseudo-selector?

The pseudo-selector can simply be styled to display the modal as in the snippet below ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

#modal {
  display: none; /* This hides the element, this can be any property that hides the element initially, properties like opacity and visibility. */

#modal:target {
  display: block; /* This shows the element, you simply revert any properties hiding the element */

Using CSS to display modals is that simple, but how do we close the modal?

Using the same trick we used to open it, we can wrap the close button or the background overlay with another anchor tag with a link to another part of the page thus removing the :target pseudo-selector from the modal.

A sample code snippet on its usage below๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

Special thanks for reading my article, hoping to improve in subsequent ones :)

Share this