方法一: 内边距(padding)

方法二: 行高 (line-height)

方法三: 定位 (position, transform)

   html: 

<div class="box">
    <div class="content">
        <p>测试垂直居中效果测试垂直居中效果</p>
        <p>测试垂直居中效果测试垂直居中效果</p>
    </div>
</div>

  css: 

    .box {
            margin:0 auto;
            width: 300px;
            height: 300px;
            background: #000;
            position: relative;
        }
        .box .content {
            color: red;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            -webkit-transform: translate(-50%, -50%);
            -ms-transform: translate(-50%, -50%);
            -moz-transform: translate(-50%, -50%);
        }

效果图:

  内容垂直居中

 

 

方法四: 模拟表格(display: table;)

  css: 

        .box {
            display:table;
            width:300px;
            height:300px;
            background:#000;
            margin:0 auto;
            color:red;
        }
        .box .content {
            display:table-cell; 
            vertical-align:middle;
            text-align: center;
        }                

效果图: 

    内容垂直居中

 

方法五: 盒子(box)

  css: 

       .box {
            width: 300px;
            height: 200px;
            padding: 10px;
            border: 1px solid #ccc;
            background:#000;
            color:#fff;
            margin: 20px auto;


            display: -webkit-box;
            -webkit-box-orient: horizontal;
            -webkit-box-pack: center;  //start center end -->左 中 右
            -webkit-box-align: center;  //start center end -->上 中 下

            display: -moz-box;
            -moz-box-orient: horizontal;
            -moz-box-pack: center;
            -moz-box-align: center;

            display: -o-box;
            -o-box-orient: horizontal;
            -o-box-pack: center;
            -o-box-align: center;

            display: -ms-box;
            -ms-box-orient: horizontal;
            -ms-box-pack: center;
            -ms-box-align: center;

            display: box;
            box-orient: horizontal;
            box-pack: center;
            box-align: center;
        }

效果图: 

内容垂直居中

 

相关文章:

  • 2022-01-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-12
  • 2021-04-15
猜你喜欢
  • 2021-10-11
  • 2021-12-22
  • 2021-12-10
  • 2021-12-04
  • 2021-12-04
  • 2021-12-10
  • 2022-12-23
相关资源
相似解决方案