div水平居中 垂直居中

王朝学院·作者佚名  2016-05-24
窄屏简体版  字體: 小  |  中  |  大  |  超大  

div水平居中 垂直居中水平居中

方案一:

使用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 这样简单的设置是不行的..

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航