[Note]CSS vertical centering using float&clear

posted on 09 Nov 2008 11:03 by ilumin  in useful

HTML 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 พอดี

(เข้าใจคนเดียว)

Comment



smilebig smileopen-mounthed smileconfused smilesad smileangry smiletonguequestionembarrassedsurprised smilewinkdouble winkcry

wink คนอื่นอาจจะเข้าใจ... แต่ตุ้มเป๊ะอ่านแล้ว sad smile ต้องไปแปลงก่อน

#1 By ตุ้มเป๊ะ on 2008-11-09 12:12

embarrassedงงไอ้โค้ดข้างบนอ่ะ
แต่เข้าใจคำอธิบายว่าจะทำอะไร sad smile
กำลังหาวิธีเลย ขอบคุณมากคราบบบบ

#3 By Jiam on 2008-11-26 18:40