1.关于css垂直居中的几种方式

刚开始的时候看到垂直居中就有点头大,现在写出来为后来的同学头不要再大

首先来看一下dom结构,一般是俩个容器,

<div class="container">
    <div class="t1">
                
    </div>
</div>

第一种方式 也是很常用的一种方式

贴css代码

.container{
    width: 400px;
    height: 400px;
    margin: 0 auto;
    background: lightcoral;
    position: relative;
    margin-top: 10px;
}
.container>.t1{
    position: absolute;
    height: 200px;
    width: 200px;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
    border: 1px solid white;
}

这相信很多人多会通过定位的方式是元素偏移

第二种方式  DOM结构同上

.container>.t2{
    position: absolute;
    height: 200px;
    width: 200px;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    border: 1px solid white;
}

和前一种方式原理差不多只是使用transform代替了margin

第三种方式  使用calc()也能实现

.container>.t4{
    position: absolute;
    width: 200px;
    height: 200px;
    top: calc(50% - 100px);
    /*top: -webkit-calc(50% - 100px);*/
    left: calc(50% - 100px);
    /*left: -webkit-calc(50% - 100px);*/
    border: 1px solid white;
}

第四种方式 使用flex布局 借鉴了之前的container的css dom结构也没有什么区别

<div class="container flex">
    <div class="t3">
                
    </div>
</div>

css

.flex{
    display: flex;
    justify-content: center;
    align-items: center;
                
}
.flex>.t3{
    height: 200px;
    width: 200px;
    border: 1px solid white;
}

基本上效果图都是一样如下

原文地址:https://www.cnblogs.com/famLiu/p/7196098.html