垂直居中

一,基于绝对定位的垂直居中

  方法一:position+calc(固定宽高)

  1,position:absolute;

  2,css3:calc计算属性

  calc实现:

    内容部分必须固定宽和高。

  • calc可以做用于任何具有大小的东东,比如border、margin、pading、font-size和width等属性设置动态值
  • 支持的运算单位: rem , em , percentage , px
  • 计算优先级别和数学一致

  注意:calc 内部的表达式,在使用运算符号时,两遍必须加上空格(虽然乘除可以无视,但还是建议带上)!!!!!,不然会解析错误!!

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .wrap{
            position: relative;
            width: 400px;
            height: 150px;
            border: 1px solid red;
        }
        .wrap .cont{
            position: absolute;
            top: calc(50% - 60px);
            left: calc(50% - 50px);
            width: 100px;
            height: 120px;
            background: gray;
        }

    </style>
</head>
<body>
<div class="wrap">
    <div class="cont">这个内容部分需要定宽和定高</div>
</div>
</body>

  方法二:position+transform(自适应)

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .wrap02{
            position: relative;
            width: 400px;
            height: 150px;
            border: 1px solid red;
        }
        .wrap02 .cont{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
            background: gray;
        }
    </style>
</head>
<body>
<div class="wrap02">
    <div class="cont">这个内容部分可以实现自适应</div>
</div>
</body>

二、视口垂直居中+translate(自适应)

  • 1vh表示视口高度的1%, 1vw表示视口的宽度的1%
  • 当宽度 小于 < 高度时,1vmin = 1vm, 否则 1vmin = 1vh
  • 当宽度 大于 > 高度时, 1vmax = 1vm,否则 1vmax = 1vh;
  • 内容部分必须要固定宽和高
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .wrap{
            width: 18em;
            background: lightgreen;
            padding: 1em 1.5em;
            margin: 50vh auto 0;
            transform: translateY(-50%);
        }
    </style>
</head>
<body>
<div class="wrap">
    这个只能做到视口居中
</div>
</body>

三、FlexBox(自适应)

  • 在flexbox时,用margin:auto可以实现水平和垂直居中,可以用 margin:0 auto设置水平居中;margin: auto 0设置垂直居中
  • 被居中元素的宽度和高度可以自适应
  • 也可以通过flex的align-items和justify-content来实现水平垂直居中
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .wrap01{
            display: flex;
            min-height: 10vh;
            border: 1px solid gray;
            width: 30vw;
        }
        .wrap01 .main{
            margin: auto;
            padding: 5px;
            background: lightblue;
        }
        .wrap02{
            margin-top: 10px;
            width: 28em;
            height: 10em;
            display: flex;
            align-items: center;
            justify-content: center;
            background: lightblue;
        }
    </style>
</head>
<body>
<div class="wrap01">
    <div class="main">
        flex + margin:auto实现垂直居中
    </div>
</div>
<div class="wrap02">
    flex的align-items(垂直对齐)和justify-content(水平对齐)<br/>实现垂直水平居中
</div>
</body>
原文地址:https://www.cnblogs.com/wang715100018066/p/6292510.html