zoukankan      html  css  js  c++  java
  • 几种垂直居中的方式

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

    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{
      font-size: 0;
    }
    .cont:before{ content:
    ""; display: inline-block; height: 100%;//撑开父容器 vertical-align: middle;//居中 } .cont>.inner{   display: inline-block;   // 90%;//这里设置宽度90%是因为两个同级行内块在一起的时候,之间会有3px左右的间隙,如果设置100%,在父容器固定宽度里肯定是放不下两个行内快的,就对导致div.inner换行,从而不能垂直居中
      //宽度可以是100%,但是要在父元素设置一下font-size:02016年2月24日17:06:16
      font-size: 14px;
       100%;   vertical-align: middle;//居中 }

    使用这种方法的好处是:减少额外的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;
    }

    未完待续......

      

  • 相关阅读:
    使用getopts处理Shell脚本参数
    SAP R/3 MM模块学习笔记
    应 阿成1 要求 co主要业务操作手册
    AIX磁盘管理命令
    工作中心和工艺路线
    顾问学院培训教材 TAMM ,TAPP,TASD,TACO
    十个“三角形”汉字,好看、不好认
    ALV做出的报表里更改布局里没有保存按钮的解决方法
    SAP系统内的发票校验
    修改SAP 登录后的背景图片
  • 原文地址:https://www.cnblogs.com/miss-radish/p/3678452.html
Copyright © 2011-2022 走看看