zoukankan      html  css  js  c++  java
  • css 居中问题总结

    html代码:

    <div class="box">
        <div class="box-item">
            文字
        </div>
    </div>

     

    css样式:

    一、水平居中

    .box-item{
        text-align:center;
    }

      *一般用于文字以及inline-block/inline水平居中 ,设置该值表示box-item内文字居中对齐

     

    .box-item{
        margin:0 auto;
    }

      *一般用于类似div的block水平居中,表示box-item整个div在box内水平居中对齐

     

    二、垂直居中

    • 高度等于行高,适合单行文字居中对齐
    .box-item{
        line-height:30px;
        height:30px
    }     

     

    • margin为高度一半
    .box{
        width:100%;
        height:100%;
        margin:0;
        padding:0
    }
    .box-item{
        width:100px;
        height:100px;
        border:1px solid #ccc;
        position:relative;
        top: 50%;
        margin: -150px auto 0 auto;
    }
    •  前一种方式的改良版
    .box{
        width:100%;
        height:100%;
        margin:0;
        padding:0
    }
    .box-item{
        width:100px;
        height:100px;
        border:1px solid #ccc;
        position:relative;
        top: 50%;
        margin:0 auto;
        transform: translateY(-50%);
    }

     

    • align-items存在兼容性问题
    .box {
        display: flex;
        align-items: center; 
        justify-content: center; 
    }
    .box-item {
        width: 300px;
        height: 300px;
        border: 1px solid #ccc;
    }
    • 兼容性较好的几种:
    .box-item{
        margin:auto;
        width:100px;
        height:100px;
        position:absolute;
        top:0;
        left:0;
        bottom:0;
        right:0;
    }
    .box{
        position: relative;
        height:100%;
        width:100%;
    }
    
    .box-item{
        width: 100px;
        height: 100px;
        overflow: auto;
        margin: auto;
        position: absolute;
        top: 0; left: 0; bottom: 0; right: 0;
    }
    .box{
        text-align: center;
        overflow: auto;
        height:100%;
    }
    
    .box:after,.box-item{
        display: inline-block;
        vertical-align: middle;
    }
    .box:after {
        content: '';
        height: 100%;
        margin-left: -0.25em;
    }
    
    .box-item{
        max-width: 99%;
    }
    • 表格法
    .box{
        display:table;
        width:100%;
        height:100%;
    }
    .box-item {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }

     

  • 相关阅读:
    python基础练习5-9
    python安装
    python虚拟环境
    python基础语法--逻辑实现
    python基础语法
    IDE(vscode)
    pycharm使用
    复习
    环境搭建+python基础
    ASP.NET 5行代码搞二维码
  • 原文地址:https://www.cnblogs.com/ombre/p/7382577.html
Copyright © 2011-2022 走看看