Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

CSS :focus-within pseudo-class - การจัดรูปแบบพาเรนต์เมื่อลูกโฟกัส

หากเราต้องการจัดรูปแบบองค์ประกอบพาเรนต์ (parent) เมื่อมีลูก (child) ได้รับโฟกัส เราจะใช้ CSS :focus-within pseudo-class

ตัวอย่างที่ 1: ฟอร์มที่เปลี่ยนสีเมื่อโฟกัส

<!DOCTYPE html> 
<html> 
<head> 
<style> 
form { 
  margin: 2%; 
  padding: 2%; 
  display: flex; 
  flex-direction: column; 
  background: thistle; 
} 
input { 
  margin: 2%; 
} 
form:focus-within { 
  background-color: burlywood; 
  box-shadow: 0 0 12px rgba(0,0,0,0.6) 
} 
input:focus { 
  box-shadow: 0 0 12px rgba(0,0,0,0.6) 
} 
</style> 
</head> 
<body> 
<form> 
<input type="text" placeholder="name"/> 
<input type="email" placeholder="email"/> 
</form> 
</body> 
</html>

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้:

CSS :focus-within pseudo-class - การจัดรูปแบบพาเรนต์เมื่อลูกโฟกัส

ตัวอย่างที่ 2: div ที่มี textarea และ button

<!DOCTYPE html> 
<html> 
<head> 
<style> 
div { 
  width: 40%; 
  margin: 2%; 
  padding: 2%; 
  display: flex; 
  flex-direction: column; 
  background: lavenderblush; 
} 
div > * { 
  margin: 2%; 
} 
div:focus-within { 
  background-color: aliceblue; 
  box-shadow: 0 0 12px rgba(0,0,0,0.6) 
} 
</style> 
</head> 
<body> 
<div> 
<textarea></textarea> 
<button>Click</button> 
</div> 
</body> 
</html>

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้:

CSS :focus-within pseudo-class - การจัดรูปแบบพาเรนต์เมื่อลูกโฟกัส