DEV Community

Cover image for Things you should try to do with HTML/CSS to avoid JavaScript overuse : The rule of least power
Elvis Ansima
Elvis Ansima

Posted on • Updated on

Things you should try to do with HTML/CSS to avoid JavaScript overuse : The rule of least power

The rule of least power in web development is simple: whenever possible, try to use the least powerful language suitable for a given purpose.

In other words, if something can be done with HTML, do it with HTML or move to CSS, if CSS can't, move to js 👌.

Let's go:

Custom toggle button with pure css

The key here is appearance:none

Input with autosuggestion

Note that styling the dropdown is quite complicated at the time of writing this article, maybe it won't be in the coming years.

You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist

Color picker

In the example above, we have combined autosuggestion with some custom styles. Another feature of using this native input is that you can pick a color from anywhere on your screen

In page transitions, smooth scrolling to page sections

Are you familiar with the following code snippet?

  $(".scrollTo").on('click', function(e) {
     e.preventDefault();
     var target = $(this).attr('href');
     $('html, body').animate({
       scrollTop: ($(target).offset().top)
     }, 2000);
  });
Enter fullscreen mode Exit fullscreen mode

Okay, in modern browsers you can achieve this with less code using the scrollIntoView function, but more interestingly, a single line of CSS can save your day scroll-behavior : smooth;.

Accordion/Dropdown Menu

Image Carousel

The key aspect here is the use of scroll-snaping.

Bonus : Want to see an advanced demo? :

Dialog or modal window

These need a bit of javascript code to open and close, but all this is based on a native element

Note that the browser will make sure that the modal is always on top, no matter what the highest z-index you currently have in your page, no need to calculate anything!

From the demo, we use an experimental css at-rule:@starting-style that allows us to give an initial style to an element when it is rendered for the first time, so that the element will transition from there at the beginning.

Read more about the dialog element: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog

Style a given section based on an other section in the page

We use the pseudo-class :has(), which can target parent elements based on their children : MDN article.

Conclusion

While some functionality can be achieved with pure HTML and CSS, browser support is still an issue. The best way to know if you are not screwing up the majority of your users is to check browser compatibility before using the element. You can use the caniuse website to quickly check browser support for a given html element, css property, or even more: browser APIs.

Top comments (0)