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

วิธี Center Align Layout ด้วย CSS

เรียนรู้ 2 วิธี center align webpage layout ด้วย CSS

สมมติ styling article layout อยาก center <article> แนวนอนกลางหน้า

วิธีง่ายและคลาสสิก: ใช้ margin ตั้ง left/right เป็น auto

HTML markup สำหรับ article layout:

<article> <h1>Title for your article</h1> <p> Lorem ipsum dolor sit amet... </p> </article>

CSS declaration block:

article { max-width: 640px; margin-left: auto; margin-right: auto; }

จะ center align article กลางหน้าเว็บพอดี

max-width จำเป็นต้องมี เพราะไม่มีมัน text จะ span ทั่วหน้า

Center Align Horizontally ด้วย Flexbox

ใช้ modern flexbox property ได้ เพราะ flexbox ส่ง properties ลง child elements วิธีง่ายสุดคือ wrap <article> ใน element ใหม่ แล้วเพิ่ม flexbox properties ให้ parent ใหม่

Wrap article ด้วย <main>:

<main> <article> <h1>Title for your article</h1> <p> Lorem ipsum... </p> </article> </main>

ย้าย flexbox properties (ไม่รวม max-width) จาก article { } ไป main { }:

main { display: flex; flex-direction: column; justify-content: center; align-items: center; } article { max-width: 640px; }

ทำงานเหมือน margin: auto เดิมพอดี