例子:css
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>css實現子層在父層中水平垂直居中</title> <style type="text/css"> #parent { position:absolute; top:50%; left:50%; margin:-250px 0 0 -200px; height:500px; width:400px; background-color:red; } #child { position:absolute; top:50%; left:50%; margin:-100px 0 0 -150px; height:200px; width:300px; background-color:green; } </style> </head> <body> <div id="parent"> <div id="child"></div> </div> </body> </html>
解釋:
id爲parent的層的父層是body,id爲child的層的父層是parent。
須要注意點:
一:子層必須設置position爲absolute,父層必須設置position爲relative;absolute能夠做爲另外一個absolute的父層。
二:子層top設置爲50%,left也設置爲50%。
三:子層的margin-top設置爲自己高度的一半,而且爲負值;margin-left設置爲自己寬度的一半,而且爲負值。
效果:
子層水平垂直居中於父層。html