css如何快速实现水平垂直居中?快来get起来!

垂直居中是布局中十分常见的效果之一,在进行编辑过程中经常遇到,如何在已知元素的宽度和高度及未知的情况下,css快速实现水平垂直居中呢?春哥团队小编为您分享如下,有需要的快点学起来吧。


html结构:

<div class="parent">
    <div class="item"></div>
</div>

1. 已知元素的宽度和高度:

.item {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -75px; /* 设置margin-left / margin-top 为自身高度的一半 */
    margin-left: -75px;
}
.item {
    position: absolute;
    margin:auto;
    left:0;
    top:0;
    right:0;
    bottom:0;
}

/* 这个方法可以实现自适应 */

2. 未知元素的高度和宽度:

.item {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); /* 使用css3的transform来实现 */
}
.parent {
    display: flex;
    justify-content:center;
    align-items: center;
    background: #AAA;
    height: 300px;   /* 注意这里需要设置高度来查看垂直居中效果 */
}

暂时就归纳这么多,后期再不断更新、整理,欢迎大家在春哥技术源码论坛区一起讨论、交流!





来源:春哥技术博客,欢迎分享,转载请注明出处。(欢迎加春哥团队客服微信号:taike668)

本文地址:https://www.cgtblog.com/qd/3499.html
上一篇:WordPress的网站文件与Mysql数据库备      下一篇:微信小程序request:fail socket time