使块级元素居中的方式

第一种

就是用绝对定位或是fixed 这种的好处就是浏览器都兼容,但是块级元素必须固定width和height(常用方法)代码如下:

<style type="text/css">
    .box{position:absolute;top:50%;left: 50%;margin-left: -150px;margin-top:-150px;width:300px ; height:300px;background:red;}
 </style> 
<div class="box"></div>

第二种: 

就是用绝对定位或是fixed 这种是元素可以不固定width和height的大小但是必须设置它的宽高要不它的宽高就和页面一样大和ie6,ie7不兼容。(移动端常用方法)代码如下

<style type="text/css">
    .box{ width: 100px; height: 100px; position:absolute;  margin: auto; top: 0;left: 0; right: 0;bottom:0; background: red;}
</style>

<div class="box"></div>

第三种:

让父元素display设为table-cell 并且父元素和元素都不能是浮动,如果是浮动侧失效,元素是inline水平用text-align 如果是block用margin:0 auto;但是ie7以下不兼容代码如下:

 

<style type="text/css">
    .box1{ width: 300px; height: 300px; display: table-cell; vertical-align: middle; background: red; }
    .box2{ width: 100px; height: 100px; background: orange; margin:0 auto; }
</style>

<div class="box1">
    <div class="box2"></div>
</div>

 第四种:

1.子元素

 

<body>
  <div><p>What is CSS?</p></div>
</body>
div{text-align:center}
  p{display:inline-block}

 

第五种:

2.淘宝分页:

 

<body>
  <div><p>What is CSS?</p></div>
</body>
  div{position:relative; left:50%; float:left;}
  p{position:relative; left:-50%;}

 

posted @ 2016-01-21 09:16  GinJiong  阅读(165)  评论(0)    收藏  举报