웹 프론트엔드 CSS 튜토리얼 JavaScript를 버리기 위한 필수 HTML 및 CSS 요령

JavaScript를 버리기 위한 필수 HTML 및 CSS 요령

Oct 17, 2024 pm 11:34 PM

JavaScript를 사용하지 말아야 할 경우와 왜 HTML과 CSS가 작업에 더 나은 도구가 될 수 있는지 이야기해 보겠습니다. 특히 Javascript 개발자의 경우에는 반직관적으로 들릴 수도 있지만 결국에는 이해가 될 것입니다. 저를 믿으세요!

저는 자바스크립트 반대자가 아닙니다. 리치 텍스트 편집기를 위해 하루 종일 글을 씁니다. 그러나 시간이 지남에 따라 많은 작업에 HTML과 CSS를 사용하면 실제로 코드를 더 간단하고 유지 관리하기 쉽고 성능도 더 높일 수 있다는 것을 알게 되었습니다. 이 접근 방식은 최소 전력의 법칙이라고 알려진 핵심 웹 개발 원칙에 뿌리를 두고 있습니다.

최소 전력의 법칙

최소 전력의 규칙은 간단합니다. 작업에 적합한 가장 강력한 언어를 사용하는 것입니다. 웹 개발에서 이는 가능한 경우 CSS 대신 HTML을 사용하고 JavaScript 대신 CSS를 사용하는 것을 의미합니다. 여기서의 논리는 다음과 같습니다.

  • HTML은 선언적이고 가벼우며 콘텐츠 구조화에 적합합니다.
  • CSS도 선언적이며 스타일 지정에 사용되며 JavaScript가 필요하지 않은 다양한 레이아웃 및 상호 작용 옵션을 제공합니다.
  • JavaScript는 강력하기는 하지만 복잡성, 성능 비용 및 잠재적인 오류를 초래합니다.

이제 GitHub 저장소에서 사용할 수 있는 몇 가지 실제 사례를 살펴보겠습니다. 일반적으로 JavaScript를 사용했지만 HTML 및 CSS만으로 더 나은 결과를 얻을 수 있습니다. 이 예는 기능과 성능을 유지하면서 코드를 단순화할 수 있는 방법을 보여줍니다.

예 1: 사용자 정의 스위치(JS가 없는 체크박스)

우리는 모두 맞춤형 스위치를 제작했습니다. 일반적으로 여기에는 클릭 및 토글 상태를 처리하기 위해 많은 JavaScript가 필요합니다. 그러나 HTML과 CSS만 사용하여 모든 기능을 갖춘 액세스 가능한 스위치를 구축하는 방법은 다음과 같습니다.

ssential HTML and CSS Tricks to Ditch JavaScript

Github 레포

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);
}
로그인 후 복사

이 설정은 스타일 변경을 위해 :checked 의사 클래스를 활용하여 JavaScript 없이 완전한 기능을 갖춘 스위치를 생성합니다. 이 의사 클래스는 "선택된" 상태에 있는 요소(체크박스)를 대상으로 합니다. 체크박스가 켜져 있을 때 배경색 변경, 슬라이더 버튼 이동 등 스위치의 스타일 변경을 트리거합니다.

이것이 더 나은 이유:

  • JavaScript가 필요하지 않습니다. 움직이는 부품이 적고 버그가 발생할 가능성이 적습니다.
  • 즉시 액세스 가능: 키보드와 마우스가 자동으로 지원되므로 유지 관리가 더 쉽습니다.

예 2: 를 사용한 자동 제안

자동 완성 기능은 라이브러리나 맞춤 JavaScript를 사용하여 수행되는 경우가 많습니다. 하지만 HTML의 요소를 사용하면 최소한의 노력으로 자동 제안 입력을 생성할 수 있습니다.

ssential HTML and CSS Tricks to Ditch JavaScript

Github 레포

HTML

<input type="text" list="suggestions" placeholder="Choose an option...">
<datalist id="suggestions">
  <option value="Open AI">
  <option value="Open Source">
  <option value="Open Source Software">
</datalist>
로그인 후 복사

CSS

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

input {
  padding: 10px;
  font-size: 18px;
  width: 100%;
  box-sizing: border-box;
}
로그인 후 복사

여기서 사용자가 텍스트 입력에 입력을 시작할 때 제안 목록을 제공합니다. JavaScript 기반 자동완성 라이브러리가 필요하지 않습니다.

이것이 더 나은 이유:

  • 경량: 브라우저에 내장되어 있어 더 빠르고 효율적입니다.
  • 간단함: 추가 JS, 종속성 또는 복잡한 논리가 필요하지 않습니다.

예 3: CSS를 사용한 부드러운 스크롤

많은 웹사이트에서는 웹페이지의 부드러운 스크롤이 jQuery나 맞춤 JavaScript 기능으로 처리되었습니다. 하지만 이제는 CSS 한 줄로 이를 달성할 수 있습니다.

ssential HTML and CSS Tricks to Ditch JavaScript

Github 레포

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>Section 1</h2>
</section>

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

<!-- Section 3 -->
<section id="section3">
  <h2>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;
}
로그인 후 복사

사용자가 섹션의 앵커 링크를 클릭하면 페이지가 해당 섹션으로 원활하게 스크롤됩니다.

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

<body>
     <!-- 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>Welcome to Section 1</h2>
    </section>

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

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

    <!-- Section 4 -->
    <section id="section4">
        <h2>Welcome to Section 4</h2>
    </section>
</body>
로그인 후 복사

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!

위 내용은 JavaScript를 버리기 위한 필수 HTML 및 CSS 요령의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Google 글꼴 변수 글꼴 Google 글꼴 변수 글꼴 Apr 09, 2025 am 10:42 AM

Google Fonts가 새로운 디자인 (트윗)을 출시 한 것을 볼 수 있습니다. 마지막 큰 재 설계와 비교할 때 이것은 훨씬 더 반복적 인 느낌이 듭니다. 차이를 간신히 말할 수 있습니다

HTML, CSS 및 JavaScript로 애니메이션 카운트 다운 타이머를 만드는 방법 HTML, CSS 및 JavaScript로 애니메이션 카운트 다운 타이머를 만드는 방법 Apr 11, 2025 am 11:29 AM

프로젝트에 카운트 다운 타이머가 필요한 적이 있습니까? 그런 것은 플러그인에 도달하는 것이 당연하지만 실제로는 훨씬 더 많습니다.

HTML 데이터 속성 안내서 HTML 데이터 속성 안내서 Apr 11, 2025 am 11:50 AM

HTML, CSS 및 JavaScript의 데이터 속성에 대해 알고 싶었던 모든 것.

플렉스 레이아웃의 자주색 슬래시 영역이 잘못된 '오버플로 공간'으로 간주되는 이유는 무엇입니까? 플렉스 레이아웃의 자주색 슬래시 영역이 잘못된 '오버플로 공간'으로 간주되는 이유는 무엇입니까? Apr 05, 2025 pm 05:51 PM

플렉스 레이아웃의 보라색 슬래시 영역에 대한 질문 플렉스 레이아웃을 사용할 때 개발자 도구 (d ...)와 같은 혼란스러운 현상이 발생할 수 있습니다.

CSS를 통해 일류 이름 항목으로 자식 요소를 선택하는 방법은 무엇입니까? CSS를 통해 일류 이름 항목으로 자식 요소를 선택하는 방법은 무엇입니까? Apr 05, 2025 pm 11:24 PM

요소 수가 고정되지 않은 경우 CSS를 통해 지정된 클래스 이름의 첫 번째 자식 요소를 선택하는 방법. HTML 구조를 처리 할 때 종종 다른 요소를 만듭니다 ...

SVG에서 타탄 패턴을 생성하는 정적 사이트를 만드는 방법 SVG에서 타탄 패턴을 생성하는 정적 사이트를 만드는 방법 Apr 09, 2025 am 11:29 AM

타탄은 일반적으로 스코틀랜드, 특히 세련된 킬트와 관련된 패턴의 천입니다. tartanify.com에서 우리는 5,000 개가 넘는 타탄을 모았습니다

Sass를 더 빨리 만들기위한 개념 증명 Sass를 더 빨리 만들기위한 개념 증명 Apr 16, 2025 am 10:38 AM

새로운 프로젝트가 시작될 때, Sass 컴파일은 눈을 깜박이게합니다. 특히 BrowserSync와 짝을 이루는 경우 기분이 좋습니다.

Safari의 로컬 웹 페이지에서 맞춤형 스타일 시트가 적용되지만 Baidu 페이지에서는 그렇지 않은 이유는 무엇입니까? Safari의 로컬 웹 페이지에서 맞춤형 스타일 시트가 적용되지만 Baidu 페이지에서는 그렇지 않은 이유는 무엇입니까? Apr 05, 2025 pm 05:15 PM

Safari에서 사용자 정의 스타일 시트 사용에 대한 토론 오늘 우리는 Safari 브라우저에 대한 사용자 정의 스타일 시트 적용에 대한 질문에 대해 논의 할 것입니다. 프론트 엔드 초보자 ...

See all articles