zoukankan      html  css  js  c++  java
  • CSS实现水平垂直居中

    <div class="wrapper">
        <div class="content"></div>
    </div>

    一、水平居中

    1. 行内元素:对其父元素应用text-align:center属性
    1. .wrapper{
          text-align: center;
      }
    2. 块级元素:对自身应用margin:auto属性
      .content{
          width: 200px;
          margin: 0 auto;
      }

    二、水平垂直居中

    1. 元素固定尺寸
      • 一般
        .content{
            width: 400px;
            height: 200px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -100px;
            margin-left: -200px;
        }
      •  使用calc()
        .content{
            width: 400px;
            height: 200px;
            position: absolute;
            top: calc(50% - 100px);
            left: calc(50% - 200px);
        }
    2. 元素尺寸由内容决定
      • 绝对定位
        .content{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        [注意]

        • 当居中元素的高度超过了视口,则它的顶部会被视口裁切掉
        • 在某些浏览器中,会导致元素显示有一些模糊,用transform-style:preserce-3d修复
      • 不使用绝对定位
        .content{
            margin: 50vh auto 0;
            transform: translateY(-50%);
        }

        [注意]

        • 视口相关长度单位  vw: 1vw为视口宽度的1%; vh: 1vh为视口高度的1%
        • 当视口宽度小于高度时,1vmin等于1vw,否则等于1vh
    3. Flexbox伸缩盒 
      • one
        .wrapper{
            display:flex;
            min-height: 100vh;
            margin: 0;
        }
        
        .content{
            margin: auto;
        }

        [注意]".content"元素不需要指定宽度,这个元素分配到的宽度等于max=content

      • two
        .wrapper{
            display: flex;
            align-item: center;
            justify-content: center;
        }
  • 相关阅读:
    事务传播机制,搞懂。
    洛谷 P1553 数字反转(升级版) 题解
    洛谷 P1200 [USACO1.1]你的飞碟在这儿Your Ride Is Here 题解
    洛谷 P1055 ISBN号码 题解
    洛谷 P2141 珠心算测验 题解
    洛谷 P1047 校门外的树 题解
    洛谷 P1980 计数问题 题解
    洛谷 P1008 三连击 题解
    HDU 1013 题解
    HDU 1012 题解
  • 原文地址:https://www.cnblogs.com/dxchen/p/7724172.html
Copyright © 2011-2022 走看看