盒子在页面内居中

在布局页面的时候,有时候会遇到让一个盒子水平和垂直方向上都居中,如果手动调整盒子的位置,未免太复杂了一些,下面介绍两种方法,很轻松就能做到盒子的水平和垂直方向的居中:

定位的盒子居中

第一种方法:需要知道盒子的宽高
div{
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -100px 0 0 -100px;
     width: 200px;
    height: 200px;
}
第二种方法:不需要知道div的宽高,但是不兼容IE低版本浏览器
div{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0
    margin: auto;
 }

浮动的盒子居中

一、使用margin值将浮动的盒子挤到中间位置
div{
    width:300px;
    height: 300px;
    margin: 300px;

 }
二、让父元素居中
父元素:
.father{
    width: 200px;
    height: 200px;
    margin: 0 auto;
    float:left;
}
.son{
    width:100px;
    height:100px;
    float:left;
}
posted @ 2017-06-29 19:42  rainbow8590  阅读(944)  评论(0编辑  收藏  举报