水平居中
方案一:
使用margin:0 auto
<!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>test</title><style type="text/css"> body{margin:0;padding: 10px;} .wrap{width: 600px;height: 400px;position: absolute;border:1px solid #333;} .box{position: relative;margin:0 auto;width:300px;height:150px;background-color: #999;text-align: center;}</style></head><body> <div class="wrap"> <div class="box">hello</div> </div></body></html>
方案二:
使用:
left:50%;top:50%;margin-left:-width/2;margin-top:-height/2;
定位一半后,再负边距左移和上移。达到水平和垂直方向居中效果
<!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>test</title><style type="text/css"> body{margin:0;padding: 10px;} .wrap{width: 600px;height: 400px;position: absolute;border:1px solid #333;} .box{position: absolute;left:50%;top:50%;margin-left:-150px;margin-top:-75px;width:300px;height:150px;background-color: #999;text-align: center;}</style></head><body> <div class="wrap"> <div class="box">hello</div> </div></body></html>
tip:若想垂直居中,margin:auto auto 这样简单的设置是不行的..