[Note]CSS vertical centering using float&clear
posted on 09 Nov 2008 11:03 by ilumin in usefulHTML structure
body
+ <div.distance></div>
+ <div.container>...data...</div>
CSS
* { padding: 0; margin: 0; } // reset all style padding, margin to 0
html, body { height: 100%; } // set document heightto 100%.distance {
height: 50%; // set this obj height to 50% of document
margin-bottom: -30em; // set obj margin to -half of container's height (-margin จะกินพื้นที่ที่อยู่ในตัว obj ทำให้ obj เลื่อนขึ้นไปด้านบน)
flaot: left;
}.container {
margin: 0 auto; // set this obj to herizontal center
position: relative; clear: left; // set obj in front of .distance
height: 60em;
}
see example @ http://d-graff.de/fricca/center.html
อธิบาย
ให้ความสูงของ document = y1
ความสูงของ container = y2
การจะทำให้ container อยู่กึ่งกลางแกน y ได้จะต้องหา (y2-y1)/2 (เป็น empty space ด้านบน,ล่าง)
ดังนั้นจึงสร้าง distance ให้มีความสูง = y1/2
และมี margin-bottom = y2/2 (ก็จะทำให้ความสูงของ distance = y1/2-y2/2 = (y1-y2)/2 )
ดังนั้น obj ที่อยู่ด้านบนของ container ก็จะกินพื้นที่ที่เป็น empty space ด้านบนไปแล้ว
container จึงอยู่กึ่งกลางแกน y พอดี
(เข้าใจคนเดียว)
งงไอ้โค้ดข้างบนอ่ะ
#1 By ตุ้มเป๊ะ on 2008-11-09 12:12