Skip to content
Grok

CSS with HTML

การใช้ CSS กับ HTML มี 3 วิธีหลัก:

html
<!-- วิธีที่ 1: Inline CSS - เขียน CSS โดยตรงในแอตทริบิวต์ style ของ element -->
<p style="color: blue; font-size: 18px;">ข้อความสีฟ้า</p>

<!-- วิธีที่ 2: Internal CSS - เขียน CSS ภายในแท็ก <style> ในส่วน <head> -->
<head>
  <style>
    p {
      color: red;
      font-size: 16px;
    }
  </style>
</head>

<!-- วิธีที่ 3: External CSS - แยก CSS เป็นไฟล์ต่างหากและเชื่อมโยงด้วย <link> -->
<head>
  <link rel="stylesheet" href="styles.css">
</head>

CSS with JavaScript

JavaScript สามารถจัดการ CSS ได้หลายวิธี:

js
// วิธีที่ 1: เปลี่ยนสไตล์โดยตรงผ่าน style property
document.getElementById("myElement").style.color = "red";

// วิธีที่ 2: เพิ่ม class - ใช้เมื่อต้องการเพิ่มกลุ่มสไตล์ที่กำหนดไว้แล้ว
document.getElementById("myElement").classList.add("active");
document.getElementById("myElement").classList.remove("disabled");

// วิธีที่ 3: สลับ class - เปิด/ปิดสถานะของ class (เพิ่มถ้ายังไม่มี, ลบถ้ามีอยู่แล้ว)
document.getElementById("myElement").classList.toggle("highlight");

CSS with Frontend Framework

jsx
// วิธีที่ 1: CSS Modules - แยกไฟล์ CSS เป็นโมดูลเฉพาะคอมโพเนนต์
import styles from "./Button.module.css";

function Button() {
  return <button className={styles.button}>คลิกที่นี่</button>;
}
vue
<template>
  <div class="container">
    <button @click="count++">คลิกที่นี่: {{ count }}</button>
  </div>
</template>

<script setup>
import { ref } from "vue";
const count = ref(0);
</script>

<style scoped>
/* scoped ทำให้ CSS นี้ใช้ได้เฉพาะในคอมโพเนนต์นี้เท่านั้น ไม่ส่งผลกระทบกับคอมโพเนนต์อื่น */
.container {
  margin: 20px;
}
button {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
}
</style>
vue
<template>
  <div class="container">
    <button @click="count++">คลิกที่นี่: {{ count }}</button>
  </div>
</template>

<script setup>
import { ref } from "vue";
const count = ref(0);
</script>

<style scoped>
/* scoped ทำให้ CSS นี้ใช้ได้เฉพาะในคอมโพเนนต์นี้เท่านั้น ไม่ส่งผลกระทบกับคอมโพเนนต์อื่น */
.container {
  margin: 20px;
}
button {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
}
</style>