码迷,mamicode.com
首页 > 其他好文 > 详细

几种垂直居中的方式

时间:2015-07-16 23:55:46      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

一、内容高度不固定,容器高度固定,要使内容在容器中垂直居中

a.使用空标签

<div class="cont">
    <div class="inner">比较满意比较满意比较满意</div><div class="v">cssHack</div>
</div>
技术分享
* {
    margin: 0;
    padding: 0;
}
.cont {
    background-color: #ccc;
    font-size: 24px;
    height: 150px;
    text-align: center;
    overflow: hidden;
    width: 280px;
}
.cont .inner,
.cont .v {
    display: inline-block;
    zoom: 1;*display: inline; /* 用于触发支持IE67 inline-block */
}
.cont .inner {            
    line-height: 1.8;
    padding: 0 4px 0 5px;
    vertical-align: middle;
    width: 262px;           
}
.cont .v {
    line-height: 150px;
    text-indent:-9999px;
    width: 1px;         
}
View Code

效果:

技术分享

b.使用伪元素

<div class="cont">
    <div class="inner">比较满意比较满意比较满意</div>
</div>

css代码是:

.cont:before{
    content: "";
    display: inline-block;
    height: 100%;//撑开父容器
    vertical-align: middle;//居中
}
.cont>.inner{
  display: inline-block;
  width: 90%;//这里设置宽度90%是因为两个同级行内块在一起的时候,之间会有3px左右的间隙,如果设置100%,在父容器固定宽度里肯定是放不下两个行内快的,就对导致div.inner换行,从而不能垂直居中
}

使用这种方法的好处是:减少额外的html标签。对于有代码洁癖的人来说,这种方法很不错,不过这种伪元素似乎不兼容ie6,7。

二、子容器要在父容器中垂直居中,子容器高度固定

这种情况可以采用相对定位和绝对定位来完成

给父容器相对定位,子容器绝对定位,子容器top:50%,margin-top:-自身高度的一半

<div class="cont">
    <div class="inner"></div>
</div>
.cont{
    position: relative;
    width:150px;
    height: 300px;
    background-color: #eee;
}
.cont>.inner{
    position: absolute;
    top: 50%;
    margin-top: -50px;
  //以下注释内容为水平垂直居中
  /*top: 50%;
  left:50%;
  margin-left:-50px;//负自身宽度的一半
    margin-top: -50px;//负自身高度的一半*/
    width: 100px;
    height: 100px;
    background-color: #000;
}

 

 三、绝对定位元素的居中--margin:auto(ie8+以及其他浏览器可用)

.cont{
    position: relative;
    width:150px;
    height: 300px;
    background-color: #eee;
}
.cont>.inner{
    position: absolute;
  top:0;
  bottom:0;
  margin: auto 0;
  //以下注释的为水平垂直居中
    /*top: 0;
    bottom:0;
    left: 0;
    right: 0;
    margin: auto;*/
    width: 80%;
    height: 100px;
    background-color: #000;
}

 

 

未完待续......

  

几种垂直居中的方式

标签:

原文地址:http://www.cnblogs.com/miss-radish/p/3678452.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!