首页 > Web开发 > 详细

CSS垂直水平居中

时间:2019-08-16 19:44:12      阅读:64      评论:0      收藏:0      [点我收藏+]

                 技术分享图片

  [已知宽高]

  1. 已知宽高 [父元素相对定位,子元素绝对定位 top left margin-top margin-left]
    .box {
        position: relative;
        width: 300px;
        height: 300px;
        border: 1px solid #000;
    }
    .center {
        background-color: red;
        width: 100px;
        height: 100px;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -50px;
        margin-left: -50px;
    }

  2.已经知宽高[父元素相对定位,子元素绝对定位 top为0,bottom为0,left为0,right为0,margin为auto]

    .box{
        width:300px;
        height:300px;
        border:1px solid black;
        position: relative;
    }
    .center{
        background: red;
        width:100px;
        height:100px;
        margin:auto;
        bottom: 0;
        top:0;
        left:0;
        right:0;
        position: absolute;
    }

  [未知宽高]

  1.未知宽高[CSS3的transform,绝对定位,top为50%,left为50%] transform只兼容到IE9

 .box{
        width:300px;
        height:300px;
        border:1px solid black;
        position: relative;
    }
    .center{
        background: red;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%)
    }

  2.未知宽高[flex布局,justify-content: center;align-items: center;]  flex只兼容到IE10

 .box{
        width:300px;
        height:300px;
        border:1px solid black;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .center{
        background: red;
    }

  

有两种情况:

情况一:内容不过多,可是实现垂直水平居中                                                       情况二:内容过多的话,只能实现垂直居中(如果想实现水平垂直居中,需要定宽)

技术分享图片                                           技术分享图片

 

CSS垂直水平居中

原文:https://www.cnblogs.com/chorkiu/p/11365505.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!