CSS Nesting — เขียน nested selector ได้เหมือน Sass โดยไม่ต้องใช้ preprocessor
Native CSS nesting ใช้ & แทน parent selector เหมือน Sass/SCSS — build tool ไม่จำเป็นอีกต่อไปสำหรับ nested CSS
เมื่อก่อนต้องใช้ Sass หรือ PostCSS เพื่อเขียน nested selector ตอนนี้ browser รองรับ native แล้ว:
/* ก่อน — ต้องเขียนแบบแบน */
.card { background: white; }
.card:hover { background: #f8fafc; }
.card .card-title { font-size: 1.2rem; }
.card .card-title a { color: inherit; }
/* ตอนนี้ — nest ได้เลย */
.card {
background: white;
&:hover { background: #f8fafc; }
.card-title {
font-size: 1.2rem;
a { color: inherit; }
}
}
& คือ reference ถึง parent selector — ต้องใช้เมื่อ nest pseudo-class (:hover, :focus) หรือ pseudo-element (::before)
.btn {
padding: 0.5rem 1rem;
&:hover { opacity: 0.8; } /* .btn:hover */
&::after { content: '→'; } /* .btn::after */
&.is-active { font-weight: bold; } /* .btn.is-active */
}
Support: Chrome 112+, Firefox 117+, Safari 17.2+ — ใช้ใน production ได้แล้ว