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

การหมุน Elements ด้วย CSS rotate()

CSS rotate() function เงี้ยน element ด้วยองศาที่กำหนด หมุน clockwise ด้วย positive degrees หรือ anti-clockwise ด้วย negative degrees

วันนี้เรียนรู้การหมุน elements ด้วย CSS ทำไมต้องหมุน element? การหมุนทำให้ web page interactive มากขึ้น ใช้ถูกต้อง rotating element จะเพิ่ม aesthetics ของ site

ขณะอ่าน โปรดอ้างอิง repo ที่เกี่ยวข้อง เพื่อดู concepts ใน action การรู้วิธีหมุน element จะเป็น valuable addition ใน CSS toolbox

CSS rotate()

CSS rotate() function ให้หมุน element บน 2D axis rotate() รับ argument หนึ่ง: angle ที่ต้องการหมุน web element หมุน clockwise หรือ counter-clockwise ได้

Syntax ของ rotate() function:

transform: rotate(angle);

ค่า "angle" = จำนวนองศาที่ element ควรหมุน ระบุ clockwise ด้วย positive degree (เช่น 45) หรือทิศตรงข้ามด้วย negative degree (เช่น -39)

rotate() function ใช้กับ HTML element ใดๆ ได้ เช่น หมุน paragraph of text หรือหมุน image

HTML rotate ปรากฏทันที render page ไม่มี visible rotation เพื่อดู rotation ใน action ควรใช้ CSS transition Transitions เปลี่ยน state ของ element เมื่อมี action เช่น cursor hover

rotate() CSS Example

สร้าง HTML page สำหรับวาง rotating box ใส่ box เป็น div ให้ class "rotate"

<div class="rotate"></div>

เพิ่ม styling:

div.rotate { width: 50px; height: 50px; background-color: chocolate; }

Refresh ได้ colored box พร้อมสำหรับ rotate() function

การหมุน Elements ด้วย CSS rotate()

เพื่อหมุน box ต้องพูดถึง transform property ก่อน

CSS transform function ตามชื่อ transform elements หนึ่งใน functions ที่ใช้ได้คือ rotate() transform property รับ functions หลายอย่าง ทำได้หลายอย่าง rotate แค่หนึ่งในนั้น

rotate function เลื่อน element รับ argument: จำนวนองศาที่ต้องการเงี้ยน element ลอง apply 35-degree positive rotation:

div.rotate { width: 50px; height: 50px; background-color: chocolate; transform: rotate(35deg); }

หมุน box แล้ว! ยินดีด้วย

การหมุน Elements ด้วย CSS rotate()

เมื่อไหร่ควรใช้ CSS Transform rotate() Function

Rotate อนุญาต fancy UI ideas หรือ rotating images เช่น หมุนภาพ 180 degrees หากต้องการ rotated image ที่อื่น save แล้วใช้ต่อ

อีกอย่างที่หมุนได้คือ text สมมติสร้าง layout mimic magazine สามารถหมุน text เน้น text elements

ไม่ได้แค่นี้ rotate() ทำ animations ที่ cool ได้!

มาใช้ CSS :hover selector บน div ใส่ rotation effect:

.rotate:hover { transform: rotate(35deg); background-color: deeppink; }

สนุกใช่ไหม? 😺

การหมุน Elements ด้วย CSS rotate()

Box หมุนเมื่อ hover ด้วย mouse ใช้ background-color CSS property เปลี่ยนสี box ตอน hover

สรุป

CSS rotate() function ทำให้ web element ปรากฏมุมเอียง function รับ argument หนึ่ง: จำนวนองศาที่ element ควรหมุน ระบุ positive หรือ negative degree values ได้

การหมุน elements ทำให้ web pages aesthetically pleasing มากขึ้น เช่น ใช้ rotate กับ box เมื่อ user hover หรือหมุน link เมื่อ user hover ขึ้นอยู่กับคุณจะใช้ skill นี้ยังไง!

สนใจเรียน CSS เพิ่ม? ดู complete How to Learn CSS guide มี expert advice และ top learning resources