美文网首页
常见的居中方式

常见的居中方式

作者: size_of | 来源:发表于2017-08-12 23:02 被阅读0次

    适用于固定宽高:

    • 利用position:absolute
    .center1{
                position: absolute;
                top: 50%;
                left: 50%;
                margin-top: -50px;
                margin-left: -50px;
                width:100px;
                height:100px;
            }
    
    • 利用position:fixed
    .center2{
                position: fixed;
                top: 50%;
                left: 50%;
                margin-top: -50px;
                margin-left: -50px;
                width:100px;
                height:100px;
            }
    

    适用于固定宽高和非固定宽高:

    • 利用position:absolute
    .center3{ 
                position:absolute; 
                width:140px; 
                height:140px; 
                top:0;
                right:0;
                bottom:0; 
                left:0; 
                margin:auto;
          }
    
    • 使用position:absolute以及css3的新属性transform:translate(x,y)
    .center4 {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                -webkit-transform: translate(-50%, -50%);
                -moz-transform: translate(-50%, -50%);
                -ms-transform: translate(-50%, -50%);
            }
    
    • 利用position:fixed
    .center5{ 
                position:fixed; 
                width:140px; 
                height:140px; 
                top:0;
                right:0;
                bottom:0; 
                left:0; 
                margin:auto;
          }
    
    • 利用display:table-cell
    .center6 {
                display: table-cell;
                vertical-align: middle;
                text-align: center;
            }
    
    • 利用伪元素和vertical-align:middle(常用语弹窗居中)
    .outbox::before{
                    content:"";
                    width:0;
                    height:100%;
                    display:inline-block;
                    vertical-align:middle;
                }
                .outbox{
                    position:fixed;
                    top:0;
                    right:0;
                    bottom:0;
                    left:0;
                    text-align:center;
                }
                .content{
                    width:200px;
                    height:200px;
                    background-color:#ccc;
                    display:inline-block;
                    vertical-align:middle;
                }
    

    相关文章

      网友评论

          本文标题:常见的居中方式

          本文链接:https://www.haomeiwen.com/subject/vdfsrxtx.html