码迷,mamicode.com
首页 > Web开发 > 详细

常用的CSS水平垂直居中方法大全

时间:2020-03-14 19:50:53      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:log   contain   transform   水平居中   遇到   方向   容器   absolute   play   

作为一名程序媛
在编写页面的时候
经常还会遇到水平或者垂直居中的一些布局
今天正好有空
就把各种居中的方式都总结了一下
分享给大家
希望能给大家带来帮助

1.已知宽高背景图与背景图上的文字都水平垂直居中

.img-bg{
    position: absolute;
    background: url("http://source.kakehotels.com/kake/frontend/img/flashsales-icon.png") no-repeat;
    width: 90px;
    height: 90px;
    background-size: 100%;
    top:0;
    bottom:0;
    left:0;
    right: 0;
    margin:auto;
    line-height: 90px;
    font-size: 12px;
    color: #fff;
}

技术图片

2.有宽度的div水平居中

.width-center{
    width: 300px;
    text-align: center;
    margin: 0 auto;
    background:pink;
}

技术图片

3.有绝对定位的div水平居中

.position-center{
    position: absolute;
    top:0;
    bottom: 0;
    width: 300px;
    height: 300px;
    margin: auto 0;
    background: pink;
    text-align: center;
}

技术图片

4.有绝对定位的div水平跟垂直都居中

.vertical-center-position{
    position: absolute;
    width: 300px;
    height: 300px;
    background: #f5f5f5;
    text-align: center;
    top:0;
    bottom:0;
    left:0;
    right: 0;
    margin:auto;
}

技术图片

5.已知宽高的容器的水平垂直方向居中

.vertical-center-width{
    width: 300px;
    height: 300px;
    position: absolute;
    background: #f5f5f5;
    text-align: center;
    top:50%;
    left: 50%;
    margin-top: -150px;
    margin-left: -150px;
}

技术图片

6.未知宽高的容器的水平垂直方向居中注:transform属性,低版本浏览器不兼容,例如IE8

.vertical-center-nowidth{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

技术图片

7.水平垂直居中记得要想到flexbox此时.div无论是否已知宽高,都能两个方向居中

.container{
    display: flex;
    align-items: center;
    justify-content: center;
}
.container div{
    color: pink;
}

8.手机端垂直居中弹框

<div class="popupBg"></div>
    <div class="popup">
    <img src="images/fudai-dialog.png"/>
</div>
.popupBg{position: fixed;top: 0;left: 0;right: 0;bottom: 0;background: rgba(0,0,0,.8);z-index: 100;}
.popup{position: fixed;top: 50%;left: 50%;transform: translate(-50%,-50%);-webkit-transform: translate(-50%,-50%);z-index: 100;background: #FFF;}

http://www.weste.net/2014/12-...
以上就是8种常用的css水平垂直居中方法,大家可以在实际项目中加以运用,

常用的CSS水平垂直居中方法大全

标签:log   contain   transform   水平居中   遇到   方向   容器   absolute   play   

原文地址:https://www.cnblogs.com/baimeishaoxia/p/12493607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!