recherche
Maisoninterface Webtutoriel CSSAstuces HTML et CSS essentielles pour abandonner JavaScript

Let’s talk about when not to use JavaScript and why HTML and CSS can often be the better tools for the job. This might sound counterintuitive—especially coming from a Javascript Developer—but it’ll make sense by the end, trust me!

I’m not anti-JavaScript. I write in it all day long for a Rich Text Editor. But over time, I’ve found that by using HTML and CSS for many tasks, I can actually make my code simpler, more maintainable, and often more performant. This approach is rooted in a core web development principle known as the rule of least power.

The Rule of Least Power

The rule of least power is simple: use the least powerful language suitable for the task. In web development, this means using HTML over CSS, and CSS over JavaScript wherever possible. The logic here is that:

  • HTML is declarative and lightweight, great for structuring content.
  • CSS is also declarative and used for styling, offering many layout and interaction options that don't need JavaScript.
  • JavaScript, while powerful, does introduce complexity, performance costs, and potential errors.

So let’s dive into some real-world examples, all of which are available in this GitHub repository, where you might have typically used JavaScript but can achieve better results with just HTML and CSS. These examples demonstrate how you can simplify your code while maintaining functionality and performance.

Example 1: Custom Switches (Checkboxes without JS)

We’ve all built custom switches. Usually, this involves a lot of JavaScript to handle clicks and toggle states. But here’s how you can build a fully functional, accessible switch using just HTML and CSS.

ssential HTML and CSS Tricks to Ditch JavaScript

Github Repo

HTML

<label class="switch">
  <input type="checkbox" class="switch-input">
  <span class="switch-slider"></span>
</label>

CSS

/* The outer container for the switch */
.switch { 
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

/* The hidden checkbox input */
.switch-input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* The visible slider (background) of the switch */
.switch-slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
}

/* The circle (slider button) inside the switch */
.switch-slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
}

/* Pseudo-class that styles the switch when the checkbox is checked */
.switch-input:checked + .switch-slider {
  background-color: #2196F3;
}

/* Moves the slider button to the right when the switch is checked */
.switch-input:checked + .switch-slider:before {
  transform: translateX(26px);
}

This setup creates a fully functional switch without JavaScript, leveraging the :checked pseudo-class for styling changes.This pseudo-class targets the element (the checkbox) when it's in the "checked" state. It triggers the style changes for the switch, such as changing the background color and moving the slider button when the checkbox is toggled on.

Why This Is Better:

  • No JavaScript needed: Fewer moving parts, fewer chances for bugs.
  • Accessible out of the box: You get keyboard and mouse support automatically, making it easier to maintain.

Example 2: Auto Suggest with

Autocomplete functionality is often done with a library or custom JavaScript. But with HTML’s element, you can create an auto-suggest input with minimal effort.

ssential HTML and CSS Tricks to Ditch JavaScript

Github Repo

HTML

<input type="text" list="suggestions" placeholder="Choose an option...">
<datalist id="suggestions">
  <option value="Open AI">
  </option>
<option value="Open Source">
  </option>
<option value="Open Source Software">
</option></datalist>

CSS

.container {
  width: 300px; 
  display: block; 
}

input {
  padding: 10px;
  font-size: 18px;
  width: 100%;
  box-sizing: border-box;
}

Here, the provides a list of suggestions when the user starts typing in the text input. No need for JavaScript-based autocomplete libraries.

Why This Is Better:

  • Lightweight: It’s built into the browser, so it’s faster and more efficient.
  • Simple: No extra JS, dependencies, or complex logic needed.

Example 3: Smooth Scrolling with CSS

In a lot of websites, smooth scrolling on a webpage was handled with jQuery or custom JavaScript functions. But now, we can achieve this with a single line of CSS.

ssential HTML and CSS Tricks to Ditch JavaScript

Github Repo

HTML

<nav>
  <a href="#section1">Go to Section 1</a>
  <a href="#section2">Go to Section 2</a>
  <a href="#section3">Go to Section 3</a>
</nav>

<!-- Section 1 -->
<section id="section1">
  <h2 id="Section">Section 1</h2>
</section>

<!-- Section 2 -->
<section id="section2">
  <h2 id="Section">Section 2</h2>
</section>

<!-- Section 3 -->
<section id="section3">
  <h2 id="Section">Section 3</h2>
</section>

CSS

/* Basic styling for sections */
section {
    height: 100vh;
    padding: 20px;
    font-size: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
}

/* Different background colors for each section */
#section1 {
    background-color: lightcoral;
}

#section2 {
    background-color: lightseagreen;
}

#section3 {
    background-color: lightblue;
}

/* Styling for the navigation */
nav {
    position: fixed;
    top: 10px;
    left: 10px;
}

nav a {
    display: block;
    margin-bottom: 10px;
    text-decoration: none;
    color: white;
    padding: 10px 20px;
    background-color: #333;
    border-radius: 5px;
}

nav a:hover {
    background-color: #555;
}

When a user clicks on a section's anchor link, this ensures that the page scrolls smoothly to that section.

Why This Is Better:

  • Less Code: Achieve smooth scrolling with a single line of CSS instead of complex JavaScript, reducing code complexity.
  • Improved Performance: Native CSS scrolling is faster and more efficient than JavaScript-based solutions.
  • Browser Consistency: CSS ensures smooth scrolling works consistently across browsers and devices.

Example 4: Accordions using
and

Accordion menus are often built with JavaScript to toggle visibility of content. But HTML provides the

and elements that give us this functionality with no extra code.

ssential HTML and CSS Tricks to Ditch JavaScript

Github Repo

HTML

<details>
  <summary>Click to toggle</summary>
  <p>This is some content!</p>
</details>

CSS

details {
  width: 300px;
  background-color: #f9f9f9;
  padding: 20px;
  border: 1px solid #ddd;
  font-size: 18px;
}

summary {
  cursor: pointer;
  font-size: 20px;
  font-weight: bold;
}

details[open] summary {
  color: #2196F3;
}

This simple markup gives us an interactive, accessible accordion that can open and close, without needing any JavaScript.

Why This Is Better:

  • Native: It’s a browser feature, so it’s faster and more reliable.
  • ** Accessible:** The browser handles focus management and interaction patterns for you.

Example 5: Scroll-Triggered Animations with CSS

Animating elements based on scroll position is often done with JavaScript libraries. But with the scroll-margin property and scroll-behavior CSS, you can create smoother, more accessible animations.

ssential HTML and CSS Tricks to Ditch JavaScript

Github Repo

HTML

     <!-- Navigation with anchor links -->
     <nav style="position:fixed; top:10px; left:10px;">
        <a href="#section1">Section 1</a>
        <a href="#section2">Section 2</a>
        <a href="#section3">Section 3</a>
        <a href="#section4">Section 4</a>
    </nav>

    <!-- Section 1 -->
    <section id="section1">
        <h2 id="Welcome-to-Section">Welcome to Section 1</h2>
    </section>

    <!-- Section 2 -->
    <section id="section2">
        <h2 id="Welcome-to-Section">Welcome to Section 2</h2>
    </section>

    <!-- Section 3 -->
    <section id="section3">
        <h2 id="Welcome-to-Section">Welcome to Section 3</h2>
    </section>

    <!-- Section 4 -->
    <section id="section4">
        <h2 id="Welcome-to-Section">Welcome to Section 4</h2>
    </section>

CSS

html {
    scroll-behavior: smooth;
}

/* Remove body margins */
body {
    margin: 0;
}

/* Full viewport height for sections with centered content */
section {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f0f0;
    transition: background-color 0.6s ease-in-out;
}

/* Styling for headings */
section h2 {
    font-size: 36px;
    margin: 0;
    transition: transform 0.6s ease, opacity 0.6s ease;
    opacity: 0;
    transform: translateY(30px);
}

/* Add margin for scroll snapping */
section:nth-child(odd) {
    background-color: #ffcccb;
}

section:nth-child(even) {
    background-color: #d0e7ff;
}

/* Scroll-triggered animation */
section:target h2 {
    opacity: 1;
    transform: translateY(0);
}

Why This Is Better

  • No JavaScript required: You can achieve smooth scroll-triggered animations with just CSS.
  • Performance: Animations are handled natively by the browser, leading to smoother, more efficient transitions without the complexity of JavaScript.
  • Simpler to maintain: Using CSS reduces the need for complex JavaScript scroll-tracking logic, making the code easier to update and maintain.

There are plenty of cases where you can avoid the complexity of JavaScript entirely by using native browser features and clever CSS tricks.

As we see the rise of AI assistants in coding and Chat-Oriented Programming, the ability to adopt and enforce simpler, declarative solutions like HTML and CSS becomes even more crucial. AI tools can generate javascript code quickly, but leveraging HTML and CSS for core functionality ensures that the code remains maintainable and easy to understand, both by humans and AI. By using the least powerful solution for the job, you not only make your code more accessible but also enable AI to assist in a more efficient and optimized way.

HTML and CSS provide powerful tools for building interactive, accessible, and responsive web components—without the need for heavy JavaScript. So next time you’re tempted to reach for JavaScript, take a moment to consider if a simpler solution using HTML and CSS might work just as well, or even better.

Check out the Github repository for all the examples in the article. Also, check out the TinyMCE blog for insights, best practices, and tutorials, or start your journey with TinyMCE by signing up for a 14-day free trial today.

Happy coding!

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Comment nous avons tagué Google Fonts et créé des goofont.comComment nous avons tagué Google Fonts et créé des goofont.comApr 12, 2025 pm 12:02 PM

Goofonts est un projet parallèle signé par un développeur-femme et un concepteur-mari, tous deux de grands fans de typographie. Nous avons marqué Google

Articles de développement Web intemporelsArticles de développement Web intemporelsApr 12, 2025 am 11:44 AM

Pavithra Kodmad a demandé aux gens des recommandations sur ce qu'ils pensaient être certains des articles les plus intemporels sur le développement Web qui ont changé

L'accord avec l'élément de sectionL'accord avec l'élément de sectionApr 12, 2025 am 11:39 AM

Deux articles ont publié exactement le même jour:

Pratiquez des requêtes GraphQL avec l'API de l'état de JavaScriptPratiquez des requêtes GraphQL avec l'API de l'état de JavaScriptApr 12, 2025 am 11:33 AM

Apprendre à créer des API GraphQL peut être assez difficile. Mais vous pouvez apprendre à utiliser les API GraphQL en 10 minutes! Et il se trouve que je suis parfait

CMSS au niveau des composantsCMSS au niveau des composantsApr 12, 2025 am 11:09 AM

Lorsqu'un composant vit dans un environnement où les données interrogent les données qui vivent à proximité, il y a une ligne assez directe entre le composant visuel et le

Définissez le type sur un cercle ... avec chemin de décalageDéfinissez le type sur un cercle ... avec chemin de décalageApr 12, 2025 am 11:00 AM

Ici, une rotation CSS légitime de Yuanchuan. Il y a ce chemin de décalage de la propriété CSS. Il était une fois, il s'appelait le chemin de mouvement, puis il a été renommé. je

What does "revert" do in CSS?What does "revert" do in CSS?Apr 12, 2025 am 10:59 AM

Miriam Suzanne explique dans une vidéo de développeur de Mozilla sur le sujet.

Les amoureux modernesLes amoureux modernesApr 12, 2025 am 10:58 AM

J'adore les trucs comme ça.

See all articles

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
3 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
3 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
3 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Comment déverrouiller tout dans Myrise
4 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

Listes Sec

Listes Sec

SecLists est le compagnon ultime du testeur de sécurité. Il s'agit d'une collection de différents types de listes fréquemment utilisées lors des évaluations de sécurité, le tout en un seul endroit. SecLists contribue à rendre les tests de sécurité plus efficaces et productifs en fournissant facilement toutes les listes dont un testeur de sécurité pourrait avoir besoin. Les types de listes incluent les noms d'utilisateur, les mots de passe, les URL, les charges utiles floues, les modèles de données sensibles, les shells Web, etc. Le testeur peut simplement extraire ce référentiel sur une nouvelle machine de test et il aura accès à tous les types de listes dont il a besoin.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) est une application Web PHP/MySQL très vulnérable. Ses principaux objectifs sont d'aider les professionnels de la sécurité à tester leurs compétences et leurs outils dans un environnement juridique, d'aider les développeurs Web à mieux comprendre le processus de sécurisation des applications Web et d'aider les enseignants/étudiants à enseigner/apprendre dans un environnement de classe. Application Web sécurité. L'objectif de DVWA est de mettre en pratique certaines des vulnérabilités Web les plus courantes via une interface simple et directe, avec différents degrés de difficulté. Veuillez noter que ce logiciel

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

Version Mac de WebStorm

Version Mac de WebStorm

Outils de développement JavaScript utiles