您的位置:首页 > Web前端 > CSS

利用css实现元素水平垂直居中的方法(分情况讨论)

2018-03-25 15:32 931 查看
首先需要说明,根据标准盒模型(这里暂且不关注低版本IE的盒模型),我们在css中设置的width指的是content-width,padding,margin,top,left这些属性为百分数时,计算的依据为父元素的content-width+left-padding+right-padding1.父div和子div都有固定宽高 情景如下:div#content在div#wrap中垂直居中<body>    <div id="wrap">        <div id="content"></div>    </div></body><style type = "text/css">    #wrap {        width: 500px;        height: 500px;        border: 1px solid #ccc;        /*添加其他padding、margin都不会对下面的方法有影响*/
    }    #content {        width: 300px;        height: 300px;        background-color: red;    }
</style方法一,flex布局  #wrap {        display: flex;         justify-content: center;         align-items: center;   }方法二,transform+absolute #wrap {        position: relative;/*如果需要可以设置为obsolute,fixed,*/ } #content {        position: absolute;        top: 50%;        left: 50%;        transform: translate(-50%,-50%);/*此处不讨论兼容性*/  }方法三,纯absolute#wrap {       position: relative;/*如果需要可以设置为obsolute,fixed,*/ } #content {<
4000
span style="font-family:Monaco;font-size:9pt;color:rgb(51,51,51);">        position: absolute;        top: 50%;        left: 50%;        margin-left:-150px;        margin-top: -150px;/*与方法二的差异在于没有使用css3的transform,不可设置为-50%,因为margin是以父元素宽度为基础计算的,设置为-50%后又回到左上角*/ }方法四,margin:auto+absolute#wrap {        position: relative;/*如果需要可以设置为obsolute,fixed,*/ } #content {        position: absolute;        top: 0;        left: 0;        right:0;
        bottom:0;        margin:auto
  }方法五,cacl计算#wrap {        position: relative;/*如果需要可以设置为obsolute,fixed,*/ } #content {        position: absolute;        top: calc(250px - 150px);/*不可用百分数,因为是以父元素宽度为基准的,所以用百分数达不到效果*/        left: calc(250px - 150px);  }方法六,table-cell这种方法需要在div#wrap和div#content之间添加一层包裹div#table-div,包裹住div#content#wrap {      display: table;} #table-div {       display: table-cell;       vertical-align: middle;        text-align: center; } #content {       display: inline-block; }②父div有固定高度,子div没有固定高度,即height:300px;width:300px去掉可以用方法一、方法二,方法六,不能使用方法三、方法四,方法五
总结方法一、方法二对子div的宽高都没有要求,无论有没有指定子div的宽高,都起作用,但对浏览器兼容性有要求方法三,方法四没有兼容性要求但是只适应于子div高度固定的情况方法五既对兼容性有要求,同时只适应于div宽高固定的情况方法六没有兼容性要求,且对子div宽高没有要求,唯一的缺点就是要包裹一层div,html结构会变复杂一些
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: